我開始學習VB編碼(已經2天)。到現在爲止還挺好。但我需要幫助將文件夾中的多個文件複製到單個指定的工作表(或活動工作表)中。我在網上查詢,並基於這一點,我能夠得到它的工作。問題是複製第一個文件後,下一個文件被複制到第一個文件數據下面的行中。我想更改下一列的代碼而不是最後一行。每個文件都是3列,所以基本上File1數據將是前3列,然後文件2將是列4-6,依此類推。這意味着每個數據的行都是相同的。我試圖修改代碼來實現這一點,但迄今沒有運氣...VBA代碼將多個文件複製到單個指定的Excel表
Sub CombineMultipleFiles()
' Path - modify as needed but keep trailing backslash
Const sPath = "C:\My_stuff\Test\"
Dim sFile As String
Dim wbkSource As Workbook
Dim wSource As Worksheet
Dim wTarget As Worksheet
Dim lRows As Long
Dim lMaxSourceRow As Long
Dim lMaxTargetRow As Long
Dim lMaxTargetColumn As Long
'Dim blnNoHeader As Boolean
Application.ScreenUpdating = False
'lMaxTargetRow = 0
Set wTarget = ActiveSheet
lRows = wTarget.Rows.Count
sFile = Dir(sPath & "*.s1p*")
Do While Not sFile = ""
Set wbkSource = Workbooks.Open(Filename:=sPath & sFile, AddToMRU:=False)
For Each wSource In wbkSource.Worksheets
lMaxSourceRow = wSource.Cells(lRows, 1).End(xlUp).Row
lMaxTargetRow = wTarget.Cells(lRows, 1).End(xlUp).Row
wSource.Range("1:" & lMaxSourceRow).Copy _
Destination:=wTarget.Cells(lMaxTargetRow + 1, 1)
Next
wbkSource.Close SaveChanges:=False
sFile = Dir
'MsgBox lMaxTargetRow
Loop
Application.ScreenUpdating = True
End Sub
謝謝你的幫助。代碼運行良好。 – user3527910