我有我的代碼,它使用一個選擇器,我選擇哪些csv文件我想從中收集數據並粘貼到我的主工作簿。但是,數據只是在我的主工作簿的B列中進行替換。我知道我必須使用.End(xlUp)或.End(xlDown),不知道把這個放在哪裏。VBA,通過多個文件循環,複製/粘貼到最後一行
這裏是我的代碼:
Option Explicit
Dim wsMaster As Workbook, csvFiles As Workbook
Dim Filename As String
Dim File As Integer
Dim r As Long
Public Sub Consolidate()
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = True
.Title = "Select files to process"
.Show
If .SelectedItems.Count = 0 Then Exit Sub
Set wsMaster = ActiveWorkbook
For File = 1 To .SelectedItems.Count
Filename = .SelectedItems.Item(File)
If Right(Filename, 4) = ".csv" Then
Set csvFiles = Workbooks.Open(Filename, 0, True)
r = wsMaster.Sheets("Sheet1").UsedRange.Rows.Count
csvFiles.Sheets(1).Range("AK:AK").EntireColumn.Copy Destination:=wsMaster.Sheets("Sheet1").Range("A:A").EntireColumn.Offset(0, 1)
csvFiles.Close SaveChanges:=False 'close without saving
End If
Next File 'go to the next file and repeat the process
End With
Set wsMaster = Nothing
Set csvFiles = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
下編輯布魯斯·韋恩
Option Explicit
Dim wsMaster As Workbook, csvFiles As Workbook
Dim Filename As String
Dim File As Integer
Dim r As Long
Public Sub Consolidate()
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = True
.Title = "Select files to process"
.Show
If .SelectedItems.Count = 0 Then Exit Sub
Set wsMaster = ActiveWorkbook
Dim copyRng As Range, destRng As Range
Dim firstRow As Long
For File = 1 To .SelectedItems.Count
Filename = .SelectedItems.Item(File)
If Right(Filename, 4) = ".csv" Then
Set csvFiles = Workbooks.Open(Filename, 0, True)
r = wsMaster.Sheets("Sheet1").UsedRange.Rows.Count
'' This is the main new part
Set copyRng = csvFiles.Sheets(1).Range("AK1:AK" & r)
With wsMaster.Sheets("Sheet1")
firstRow = .Cells(.Rows.Count, 2).End(xlUp).Row
Set destRng = .Range("A" & firstRow + 1).Offset(0, 1)
End With
copyRng.Copy destRng
''''''''''
csvFiles.Close SaveChanges:=False 'close without saving
End If
Next File
End With
Set wsMaster = Nothing
Set csvFiles = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
您是試圖將數據添加到列A中現有數據的底部,還是始終粘貼到下一個打開的列中? – jcarroll
對不起,添加到列A中的現有數據。 – Jonnyboi
等待,它粘貼到主表中,列A?不是B列? (對我來說'Offset'看起來像是要到B列,不是嗎?另外,你不能複製整個列,然後再複製整列,然後粘貼*在另一個「整列」下面。將你的'Range(「AK:AK」)'從第一個單元格(假設第一行)移動到該列中最後一個使用過的單元格。* *想要*複製'... Range(「AK1:AK 「&r)',對嗎? – BruceWayne