【问题标题】:Copy data from macro enabled workbook从启用宏的工作簿复制数据
【发布时间】:2020-06-27 10:44:30
【问题描述】:

我正在尝试将通过文件资源管理器选择的启用宏的工作簿中的数据复制到另一个使用 VBA 的工作簿中。我到目前为止的代码是:

Dim wbThisWB    As Workbook
Dim wbImportWB  As Workbook
Dim strFullPath As String
Dim lngLastRow  As Long
Dim lngLastCol  As Long

With Application.FileDialog(msoFileDialogFilePicker)
    .AllowMultiSelect = False
    .Title = "Please select a file to open:"
    .Show
    On Error Resume Next 'In case the user has clicked the <Cancel> button
        strFullPath = .SelectedItems(1)
        If Err.Number <> 0 Then
            Exit Sub 'Error has occurred so quit
        End If
    On Error GoTo 0
End With

Set wbImportWB = Workbooks.Open(strFullPath)
'code here to copy and paste tab from Import WB into the current workbook
    On Error Resume Next 'In case there's no data or tab doesn't exist
    With wbImportWB.Sheets("PSE Report")
        lngLastRow = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
        lngLastCol = .Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
        If lngLastRow > 0 And lngLastCol > 0 Then
            'If the 'lngLastRow' and 'lngLastCol' variable have been set there's data to be copied.
            'The following copies the entire range from tab 'PSE Data' in the import workbook to cell A1 in 'Sheet1' of this workbook.
            Range(.Cells(1, 1), .Cells(lngLastRow, lngLastCol)).Copy wbThisWB.Sheets("PSE Data").Cells(1, 1)
        End If
    End With
On Error GoTo 0

wbImportWB.Close False 'Close the Import WB without saving any changes.

Set wbThisWB = Nothing
Set wbImportWB = Nothing

Application.ScreenUpdating = True

该代码适用于未启用宏的工作簿,但是当打开启用宏的工作簿并选择退出宏时,启用宏弹出框打开。不知道怎么解决!

【问题讨论】:

    标签: excel vba copy


    【解决方案1】:

    您是否在Workbooks.Open 行之前尝试了Application.DisplayAlerts = False?之后别忘了启用它(重置为True)。

    或者,如果上述方法不起作用,您可以在 Workbooks.Open 之前禁用宏,然后再重新启用:

    Dim PreviousSecurity As Long
    PreviousSecurity = Application.AutomationSecurity
    Application.AutomationSecurity = msoAutomationSecurityForceDisable
    ' Your code Workbooks.Open
    Application.AutomationSecurity = PreviousSecurity 
    

    请注意,打开文件中的任何宏都将无法运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 2017-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多