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' –