Excel VBA代码:打开新工作簿,将范围复制到原始工作簿时遇到麻烦

时间:2018-06-28 12:22:54

标签: excel vba excel-vba

早上好-

我已经设法整理了一个代码,该代码将从我的原始工作簿中打开一个新工作簿,复制一个特定范围并将该范围粘贴回原始工作簿,然后关闭引用的工作簿。我已经测试了我的代码的每个部分,在我一起运行整个代码之前,它似乎工作得很好。

现在我不断得到

  

“下标超出范围”

错误,无论我尝试修改什么,都不会消失。我已尽力研究以找出差异。

一如既往,感谢StackOverflow用户,这些用户可以帮助我时刻解决我的问题!

Sub import()
  Dim x As Workbook
  Dim y As Workbook

'## Open both workbooks first:
  Set y = ThisWorkbook
    With Application.FileDialog(msoFileDialogOpen)
        .Filters.Clear
        .Filters.Add "Excel 2007-13", "*.xlsx"
        .AllowMultiSelect = False
        .Show
    End With
  Set x = ActiveWorkbook

'##Now, copy what you want from x:
  x.Sheets("QBEPaymentAdvice").Range("D13", "T60").Copy


'##Now, paste to y worksheet:
  y.Sheets("QBE").Range("A1").PasteSpecial

'##Close Workbook x
  x.Close

End Sub

1 个答案:

答案 0 :(得分:2)

尝试这种方式:

Sub import()
  Dim x As Workbook
  Dim y As Workbook

'## Open both workbooks first:
  Set y = ThisWorkbook
    With Application.FileDialog(msoFileDialogOpen)
        .Filters.Clear
        .Filters.Add "Excel 2007-13", "*.xlsx"
        .AllowMultiSelect = False

                If .Show Then
           xlFileName = .SelectedItems(1)
        Else
           'if user pressed CANCEL - exit sub
           MsgBox "User pressed CANCEL"
           Exit Sub
        End If


    End With
  Set x = Workbooks.Open(xlFileName)

'##Now, copy what you want from x:
  x.Sheets("QBEPaymentAdvice").Range("D13", "T60").Copy


'##Now, paste to y worksheet:
  y.Sheets("QBE").Range("A1").PasteSpecial

'##Close Workbook x
  x.Close

End Sub