我需要创建一个合并工作簿,打开其他excel文件,复制并粘贴一些表。
问题是这些excel文件的数量会改变它们的名称。
例如,我可能在一周内拥有这些文件: 档案A. 文件B. 文件C
和其他文件一周后: 文件B. 文件C. 档案D. 文件E
整合excel工作簿必须能够打开所有这些文件,而不必每次都修改VBA代码。
你知道吗?如果您有一个好主意,请写几个代码行谢谢
答案 0 :(得分:0)
好的,谢谢你的建议。我在目录上创建了一个循环,我发布了解决方案以供将来参考
Dim ws1 As Worksheet
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Set ws1 = Worksheets(1)
Application.ScreenUpdating = False
myPath = "C:\Desktop\Common Folder Test\"
myExtension = "*.xls"
myFile = Dir(myPath & myExtension)
Set wb2 = Workbooks("Consolidated data.xlsm")
Set ws1 = Worksheets(1)
r2 = 1
Do While myFile <> ""
Set wb = Workbooks.Open(Filename:=myPath & myFile)
i = 2
Do While i <= 4
r = 3
Do While wb.Worksheets(i).Cells(r, 3) <> ""
r = r + 1
Loop
r = r - 1
c = 1
Do While wb.Worksheets(i).Cells(2, c) <> ""
c = c + 1
Loop
c = c - 1
wb.Worksheets(i).Range(wb.Worksheets(i).Cells(2, 1), wb.Worksheets(i).Cells(r, c)).Copy
ws1.Cells(r2, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
i = i + 1
r2 = r2 + r - 1
Loop
wb.Application.CutCopyMode = False
wb.Close SaveChanges:=False
myFile = Dir
Loop
MsgBox "Task Complete!"
Application.ScreenUpdating = True