我正在尝试创建一个循环遍历文件夹中所有非txt文件的宏,打开它们,从打开的文件中复制选择,然后使用宏将其粘贴到文件中的特定工作表(取决于在哪个文件上复制)。我前两部分工作正常,但我无法让复制部分工作。它不断复制应该是粘贴文件的文件。知道我做错了吗?
Private Sub CommandButton1_Click()
Dim Path As String
Dim File As String
Dim PasteFile As String
Dim Month As String
Dim FY As String
Month = "feb"
FY = "18"
PasteFile = ThisWorkbook.Name
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Path = "[file path]"
file = Dir(Path)
Do While file <> "*.txt" Or file <> ""
If file = "[file name]" & Month & FY & ".xlsx" Then
Workbooks.Open Path & file
Workbooks(file).Worksheets("Sheet1").Activate
Range(Cells(1, 1), Cells(5, 5)).Copy
Workbooks(myFile).Worksheets("Sheet1").Activate
Cells(10, 3).PasteSpecial xlPasteValues
End If
File = Dir()
Loop
End Sub
答案 0 :(得分:0)
避免使用.Activate
和.Select
How to Avoid the Select Method in VBA & Why
Private Sub CommandButton1_Click()
Dim Path As String
Dim File As String
Dim PasteFile As String
Dim Month As String
Dim FY As String
Month = "feb"
FY = "18"
PasteFile = ThisWorkbook.Name
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Path = "[file path]"
File = Dir(Path)
Do While File <> "*.txt" Or File <> ""
If File = "[file name]" & Month & FY & ".xlsx" Then
Workbooks.Open Path & File
With Workbooks(File).Worksheets("Sheet1")
.Range(.Cells(1, 1), .Cells(5, 5)).Copy
End With
With Workbooks(myFile).Worksheets("Sheet1")
.Cells(10, 3).PasteSpecial xlPasteValues
End With
End If
File = Dir()
Loop
End Sub