1
我正尝试在窗体应用程序中编写代码,其中我可以选择多个文件并将所有选定文件的数据追加到另一个文件(主文件)中。使用VBA将多个文件复制到单个文件
下面我写了一个函数,调用单击Userform按钮。
同时运行此代码我收到自动化错误-2147221080(800401a8)
在调试时,我发现它在给错误在下面的代码行
设置rngData = shtData重新分配值。 UsedRange
有人可以帮我解决这个问题,我是新来的VBA,并没有得到错误的原因。
Function copyfiles()
Dim wbkMaster As Workbook
Dim shtMaster As Worksheet
Dim rngMaster As Range
Dim wbkData As Workbook
Dim shtData As Worksheet
Dim rngData As Range
Dim intChoice As Integer
Dim strPath As String
Dim strPath1 As String
Dim array1() As String
Dim filepath As String
Dim count As Integer
Dim i As Integer
'to select master file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
strPath = Application.FileDialog(_
msoFileDialogOpen).SelectedItems(1)
End If
Set wbkMaster = Workbooks.Open(strPath)
Set shtMaster = wbkMaster.Worksheets(1)
'to select source file(s)
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = True
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
For i = 1 To Application.FileDialog(msoFileDialogOpen _
).SelectedItems.count
strPath = Application.FileDialog(msoFileDialogOpen _
).SelectedItems(i)
filepath = filepath & strPath & ","
Next i
End If
array1 = Split(filepath, ",", -1, vbBinaryCompare)
count = i - 1
Set rngMaster = shtMaster.Range("A65536").End(xlUp).Offset(1, 0)
For j = 0 To count - 1
Set wbkData = Workbooks.Open(array1(j))
Set shtData = wbkData.Worksheets(1)
Set wbkMaster = Workbooks.Open(strPath)
Set shtMaster = wbkMaster.Worksheets(1)
Set rngData = shtData.UsedRange
' copy data across
rngData.Copy rngMaster
' simply close data
wbkData.Close False
' release objects
Set rngData = Nothing
Set shtData = Nothing
Set wbkData = Nothing
wbkMaster.Close True
Set shtMaster = Nothing
Set wbkMaster = Nothing
Next
Set rngMaster = Nothing
End Function
开启和关闭在循环中的主簿是不是一个好办法,可能是头痛的根源。尝试在数据文件循环之前打开一次,然后在循环之后保存/关闭。 –
如果我在循环之前打开一次文件并在循环之后保存,那么它不保存所有文件内容,它只保存最后一个文件的内容。 –
好的,在新代码中,尝试用'Set shtMaster = wbkMaster.Worksheets(1)'替换'Set shtMaster = wbkMaster.Worksheets.Add' –