VBA 将工作表复制到另一个打开的工作簿
VBA Copy Worksheet to a Different Open Workbook
尝试将 sheet 从一个工作簿复制到另一个工作簿时,我总是收到超出范围的错误。原来spreadsheet(Master_Data.xlsm)是什么运行的vba脚本。脚本打开另一个跨页sheet,对其进行操作,然后复制最终的 sheet 以粘贴到 Master_Data.xlsm 工作簿中。
Sub Result_Scrapper()
Dim wb As Workbook, ws As Worksheet, wbFile As Object
Dim masterBook As Workbook
Dim wsa As Worksheet
Dim year As Integer
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.GetFolder("C:\Users\Output_Spreadsheets\")
Set masterBook = Excel.Workbooks("Master_Data.xlsm")
Application.ScreenUpdating = False
For Each wbFile In fldr.Files
If fso.GetExtensionName(wbFile.Name) = "xlsm" Then
Set wb = Workbooks.Open(wbFile.Path)
'Copy sheet of interest
ActiveSheet.Copy 'Before:=ThisWorkbook.Sheets(“A”) 'tried doing it using before statement but it also caused errors
'paste sheet into masterBook spread--this is where the error comes
masterBook.Sheets(Sheets.Count).Paste
End If
masterBook.Sheets("master").Name = Right([A2], 30)
Next wbFile
有两个问题。首先,正如其他人评论的那样,您需要完全限定计数。其次,你会想在一条线上完成;你可以在之前做,但是你只是推出最后一个 sheet 是什么,如果你在之后添加它,那么 sheets 保持秩序。
尝试:
ActiveSheet.Copy After:=masterBook.Sheets(masterBook.Sheets.Count)
尝试将 sheet 从一个工作簿复制到另一个工作簿时,我总是收到超出范围的错误。原来spreadsheet(Master_Data.xlsm)是什么运行的vba脚本。脚本打开另一个跨页sheet,对其进行操作,然后复制最终的 sheet 以粘贴到 Master_Data.xlsm 工作簿中。
Sub Result_Scrapper()
Dim wb As Workbook, ws As Worksheet, wbFile As Object
Dim masterBook As Workbook
Dim wsa As Worksheet
Dim year As Integer
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.GetFolder("C:\Users\Output_Spreadsheets\")
Set masterBook = Excel.Workbooks("Master_Data.xlsm")
Application.ScreenUpdating = False
For Each wbFile In fldr.Files
If fso.GetExtensionName(wbFile.Name) = "xlsm" Then
Set wb = Workbooks.Open(wbFile.Path)
'Copy sheet of interest
ActiveSheet.Copy 'Before:=ThisWorkbook.Sheets(“A”) 'tried doing it using before statement but it also caused errors
'paste sheet into masterBook spread--this is where the error comes
masterBook.Sheets(Sheets.Count).Paste
End If
masterBook.Sheets("master").Name = Right([A2], 30)
Next wbFile
有两个问题。首先,正如其他人评论的那样,您需要完全限定计数。其次,你会想在一条线上完成;你可以在之前做,但是你只是推出最后一个 sheet 是什么,如果你在之后添加它,那么 sheets 保持秩序。
尝试:
ActiveSheet.Copy After:=masterBook.Sheets(masterBook.Sheets.Count)