我尝试使用以下代码合并第3张Excel表格中的2张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保留了First值而不是获得新值......
答案 0 :(得分:0)
以下是使用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