Excel从WB复制到另一个WB和其他

时间:2017-06-27 14:55:41

标签: excel vba excel-vba

我目前正在寻找改进我的信息中心的代码。实际上,我需要知道如何简化并使我的代码更有效率。它正在运行,但由于公司网络上某些时段的数据量/流量,日复一日的时间越来越长。 我知道使用“选择”是不对的,但我找不到问题的答案。

情况:

  1. 我在SAP上创建了我的布局,然后导出它们(默认文件名是 'Export.xls')
  2. 我转到我的主Excel文件(称为“仪表板”)和我 运行布局导出的相关WS代码
  3. 如果我不在办公室,需要捕获用户名,而其他人则需要运行该代码。
  4. 当数据从SAP Export导入我的主文件时,它会关闭SAP“导出”文件
  5. 这是我目前的代码:

    Sub PasteSAP()
    '
    ' Pull Data From SAP Export - Excel File
    '
    Dim UserName As String
    
    UserName = Environ("username")
    
       'Clear "PasteSAP" sheet in case the next one will have less data
        Range("A:O").Select
        Selection.ClearContents
    
       'Open SAP Excel file (the export)
        Workbooks.Open "C:\Users\" & UserName & "\Desktop\export.XLSX"
        Windows("export.XLSX").Activate
    
        'Copy data of the SAP Excel file
        Range("A:O").Select
        Selection.Copy
    
        'Go back to the main file and paste in the active worksheet
        Windows("Dashboard - 2017.xlsm").Activate
        Range("A:O").Select
        ActiveSheet.Paste
    
        'Close SAP Excel file
        Windows("export.XLSX").Activate
        Application.DisplayAlerts = False
        ActiveWindow.Close
    
        'Change Format
        Range("A:A").Select 'specify the range which suits your purpose
        With Selection
            Selection.NumberFormat = "General"
            .Value = .Value
           End With
    
        Dim wks As Worksheet
        Dim lastRow As Long
        Dim r As Long
    
        Set wks = ActiveSheet
        lastRow = ActiveSheet.Cells.SpecialCells(xlLastCell).Row
    
        For r = 2 To lastRow
            If wks.Cells(r, 1) <> "" Then
            wks.Cells(r, 7).NumberFormat = "General"
            wks.Cells(r, 9).Style = "Currency"
            End If
        Next r
    
         Range("A1").Select
    End Sub
    

1 个答案:

答案 0 :(得分:0)

由于您要复制整个列,因此您无需事先删除它们。

通常你不想在窗户之间跳转,因为它需要很多时间。

同时关闭ScreenUpdating可以加快速度。

请尝试以下代码:

...
Application.ScreenUpdating = False

dim wb_export as Workbook
dim ws_export_from as Worksheet, ws_export_to as Worksheet

Set wb_export = Workbooks.open("...\Export.xls")
Set ws_export_from = wb_export.Worksheets("your worksheet")
Set ws_export_to = Worksheets("Destination worksheet")

ws_export_from.range("A:O").Copy Destination := ws_export_to.Range("A:O")

wb_export.close false
set wb_export = Nothing
set ws_export_from = Nothing
set ws_export_to = Nothing
Application.ScreenUpdating = True

这应该运行得更快。

相关问题