通过dynamic表名称循环

我通过我的文件夹中的一堆文件循环,并尝试复制一个静态列并粘贴到主表。 然而,我正在循环的每张纸都是不同的名称。

我相信这部分代码必须改变:

xlsFiles.Sheets("Sheet3").Columns("20").Copy Destination:=wsMaster.Sheets("Sheet1").Range("A" & r).Offset(1, 0). 

我可以用什么来代替床单(“Sheet3”)?

以下是完整的代码:

 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, 5) = ".csv*" Then Set csvFiles = Workbooks.Open(Filename, 0, True) r = wsMaster.Sheets("Sheet1").UsedRange.Rows.Count csvFiles.Sheets(1).Columns("col name").Copy Destination:=wsMaster.Sheets("Sheet1").Range("A" & r).Offset(1, 0) 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 

在上面的评论中,@sktneer已经得到了答案。

你可以缩短和“清理”你的If部分代码,尝试下面的代码:

 If Right(Filename, 5) = ".xls*" Then Set xlsFiles = Workbooks.Open(Filename, 0, True) r = wsMaster.Sheets("Sheet1").UsedRange.Rows.Count xlsFiles.Sheets(3).Columns("20").Copy Destination:=wsMaster.Sheets("Sheet1").Range("A" & r).Offset(1, 0) xlsFiles.Close SaveChanges:=False 'close without saving End If