VBA excelmacros2文件处理合并读取错误

我试图合并两个Excel工作表内第三个与下面的代码

`Sub CommandButton1_Click() Dim MyFile As String Dim Filepath As String Filepath = "C:\temp\" MyFile = Dir(Filepath) 'MyFile = "12_10_15_par.xlxs" 'If MyFile = "12_10_15_par.xlsx" Then If MyFile = Cells(4, 2) Then Workbooks.Open (Filepath & MyFile) Worksheets("par").Range("A1:K1000").Copy ActiveWorkbook.Close ActiveSheet.Paste Destination:=Worksheets("match").Range("T1:AF1001") 'Application.CutCopyMode = False End If MyFile2 = Dir(Filepath) If MyFile2 = Cells(5, 2) Then Workbooks.Open (Filepath & MyFile2) Worksheets("ops").Range("A1:K1000").Copy ActiveWorkbook.Close ActiveSheet.Paste Destination:=Worksheets("match").Range("D1:S1001") 'Application.CutCopyMode = False End If End Sub` 

也许我做错了,因为Myfile2保持第一个值,而不是得到一个新的…

这里是如何使用Dir() ,在循环结束时注意MyFile = Dir() ,它会在循环之前在MyFile加载下一个文件名!

试试这个:

 Sub CommandButton1_Click() Dim MyFile As String, _ Filepath As String, _ oWb As Workbook, _ pWb As Workbook Filepath = "C:\temp\" Set pWb = ThisWorkbook MyFile = Dir(Filepath) Do While MyFile <> "" If MyFile <> Cells(4, 2) And MyFile <> Cells(5, 2) Then Else Set oWb = Workbooks.Open(Filepath & MyFile) If MyFile <> Cells(5, 2) Then oWb.Worksheets("par").Range("A1:K1000").Copy Destination:=pWb.Worksheets("match").Range("T1:AF1001") '4 Else oWb.Worksheets("ops").Range("A1:K1000").Copy Destination:=pWb.Worksheets("match").Range("D1:S1001") '5 End If 'Application.CutCopyMode = False oWb.Close End If MyFile = Dir() Loop End Sub