我正在循环浏览文件夹中的一堆文件并尝试复制静态列并粘贴到主表。然而,我循环的每张纸都是一个不同的名称。
我相信代码的这一部分必须改变:
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
答案 0 :(得分:1)
@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