我想从多个工作簿导入数据,所有工作簿都来自同一个工作表索引(3)。 我是vba的新手,我想出了如何打开多个文件,以及将数据从一个工作表复制到另一个工作簿中的单个文件,但我似乎无法弄清楚如何做多个文件。 我突出显示错误的位置,它告诉我“对象不支持此属性或方法”
你可以帮忙吗? 感谢Sub dataimport()
' Set Vars
Dim ArbinBook As Workbook, DataBook As Workbook
Dim i As Integer, j As Integer
Dim Caption As String
Dim ArbinFile As Variant, DataFile As Variant
' make weak assumption that active workbook is the target
Set DataBook = Application.ActiveWorkbook
' get Arbin workbook
Caption = "Please select an input file"
' To set open destination:
' ChDrive ("E")
' ChDir ("E:\Chapters\chap14")
' With Application
'Set "arbinfile" as variant, the "true" at end makes it into an array
ArbinFile = Application.GetOpenFilename(, , Caption, , True)
'Exit when canceled
If Not IsArray(ArbinFile) Then
MsgBox "No file was selected."
Exit Sub
End If
Dim targetSheet As Worksheet
Set targetSheet = DataBook.Sheets(1)
'Open for every integer i selected in the array "arbinfile"
For i = LBound(ArbinFile) To UBound(ArbinFile)
Set ArbinBook = Workbooks.Open(ArbinFile(i))
targetSheet.Range("A2", "G150").Value = ArbinBook.Sheets(3).Range("A2", "G150").Value
**ERROR at the line above**
Workbooks(DataSheet).Activate 'Reactivate the data book
Worksheets(1).Activate 'Reactivate the data sheet
ActiveWorkbook.Sheets(1).Copy _
after:=ActiveWorkbook.Sheets(1)
Workbooks(ArbinFile(1)).Activate 'Reactivate the arbin book(i)
ArbinBook.Close
Next i
Beep
End Sub
答案 0 :(得分:1)
我的直觉告诉我ArbinBook.Sheets(3)
是图表工作表,而不是工作表(或者,至少,它不是工作表)。它也可能被隐藏,但它仍然会被索引为(3)。
如果是,请将Sheets(3)
更改为Worksheets(3)
。
已添加:BTW如果为true,这也说明了为什么使用索引号不可靠。如果可能,请按名称引用工作表。 (我很欣赏这可能并非总是可行。)
已添加(来自评论)您的代码中没有任何名为DataSheet
的内容。将Option Explicit
添加到模块顶部以指示所有此类错误。
答案 1 :(得分:0)
尝试更改第Set ArbinBook = Workbooks.Open(ArbinFile(i))
行
到Set ArbinBook = Workbooks(arbinfile(i))
我可能错了,但我认为它正在尝试将您的工作簿对象设置为打开另一个工作簿的操作,而不是将其标记为工作簿。
答案 2 :(得分:-1)
Sub Multiple()
Application.DisplayAlerts = False
Application.EnableEvents = False
Dim exlApp As Excel.Application
Dim exlWb1 As Excel.Workbook
Dim exlWb2 As Excel.Workbook
Dim exlWb3 As Excel.Workbook
Dim exlWs1 As Excel.Worksheet
Dim exlWs2 As Excel.Worksheet
Dim exlWs3 As Excel.Worksheet
Set exlApp = CreateObject("Excel.Application")
Set exlWb1 = exlApp.Workbooks.Open("C:\yourpath1\file1.xls")
Set exlWb2 = exlApp.Workbooks.Open("C:\yourpath2\file2.xls")
Set exlWb3 = exlApp.Workbooks.Open("C:\yourpath3\file3.xls")
Set exlWs1 = exlWb.Sheets("Sheet1")
Set exlWs2 = exlWb.Sheets("Sheet1")
Set exlWs3 = exlWb.Sheets("Sheet1")
exlWb1.Activate
exlWb2.Activate
exlWb3.Activate
'code
exlWb.Close savechanges:=True
exlWb.Close savechanges:=True
exlWb.Close savechanges:=True
Set exlWs1 = Nothing
Set exlWs2 = Nothing
Set exlWs3 = Nothing
Set exlWb1 = Nothing
Set exlWb2 = Nothing
Set exlWb3 = Nothing
exlApp.Quit
Set exlApp = Nothing
Application.EnableEvents = True
Application.DisplayAlerts = True
End Sub