如何通过VBA将信息从一个工作簿复制到另一个工作簿?

时间:2018-08-08 16:36:09

标签: excel vba

我正在尝试通过VBA将一个excel文件中的所有信息复制到另一个文件中。我知道在堆栈上有很多这样的问题(我什至基于对this question的回答对宏进行的尝试),但是我一直遇到错误。这是我的代码:

Sub CreateUSGCRefStepDownFile()
    Dim ParametricsWB As Workbook, ThisWB As Workbook
    Dim vFile As Variant

    'set up source files
    Set ParametricsWB = ActiveWorkbook

    vFile = Application.GetOpenFilename("Excel-files (*.xls*), *.xls*", _
        1, "Select One File to Open", , False)

    If vFile = False Then Exit Sub

    Workbooks.Open vFile


    'set up destination (this one) workbook
    Set ThisWB = ThisWorkbook


    'Create new sheets and copy and paste values into it

    'check if the sheet we want to create already exists
    Dim wsCheck As Worksheet
    Dim wsCheckExists As Boolean

    Set wsCheck = ThisWB.Sheets("Parametrics")
    On Error GoTo 0
    wsCheckExists = Not wsCheck Is Nothing


    If wsCheckExists = False Then
        Dim ws As Worksheet
        With ThisWB
            Set ws = .Sheets.Add(after:=.Sheets(.Sheets.Count))
            ws.Name = "Parametrics"
        End With
    End If

    ThisWB.Worksheets("Parametrics").Range("A1:EBT40").Value = ParametricsWB.Worksheets("ParametricAnalysis").Range("A1:EBT40").Value


End Sub

代码运行平稳,直到子末尾的最后一行。我不断收到错误:“运行时错误'-2147221080(800401a8)':自动化错误”。我曾尝试查找此错误的解释,但无法理解。我认为可能与
有关 Set ThisWB = ThisWorkbook ...我尝试将其更改为
Set ThisWB = ActiveWorkbook,但是当我到达Set wsCheck = ThisWB.Sheets("Parametrics")时,这会导致错误“下标超出范围”。不太确定我在哪里出错或为什么会出错。

0 个答案:

没有答案