我今天一直坚持这个......
我有一个包含多个.xlsx文件的文件夹,名为"要修改的文件" 他们每个人都有第一张名为specificaly的表格,如" test1"例如。
我有另一个文件夹,其他.xlsx文件名为"旧文件要插入" 其中每一个都是这样称呼的:"旧的test1.xlsx",旧的test2等......
我希望我的宏浏览第一个文件夹和文件,并复制另一个文件夹中相应的旧.xlsx的第一张。
代码远没有工作,但主要问题是我在Dir行上得到了一个错误5,我认为这是因为我使用dir两次(ProcessFiles宏在另一个我不需要的情况下工作正常在DoWork子中使用Dir。)
欢迎任何帮助,因为你可以猜到我是初学者。
这是我的代码
Sub ProcessFiles()
Dim FileName, Pathname As String
Dim wb As Workbook
Pathname = ActiveWorkbook.Path & "\Files to modify\"
FileName = Dir(Pathname & "*.xlsx", vbNormal)
Do While FileName <> ""
Set wb = Workbooks.Open(FileName:=Pathname & FileName, Local:=True)
DoWork wb
wb.Close True
Set wb = Nothing
FileName = Dir 'Error 5 is here
Loop
End Sub
Sub DoWork(wb As Workbook)
Dim FileName As String
FileName = Dir(ActiveWorkbook.Path & "\Old file to insert\" & "old " & ActiveSheet.Name & ".xlsx")
If FileName = "" Then
MsgBox "File does not exist"
Else
Set wb2 = Application.Workbooks.Open(FileName)
wb2.Sheets(1).Copy After:=wb.Sheets(1)
End If
End Sub
答案 0 :(得分:1)
如您所料,在两个不同的地方同时使用Dir
正在寻找麻烦。
在子DoWork
中,您只是用来检查文件是否存在。你不需要使用它,你可以直接尝试打开工作簿并检查开放是否成功..
Sub DoWork(wb As Workbook)
Dim FileName As String
' Dont use Dir here
Filename = ActiveWorkbook.Path & "\Old file to insert\" & "old " & ActiveSheet.Name & ".xlsx"
'Try to open the file if it exists, otherwise handle the error
On Error Resume Next
Set wb2 = Application.Workbooks.Open(Filename)
If Err.Number <> 0 Then
MsgBox "File does not exist or could not open"
Else
' Now the file is open, continue work with it
wb2.Sheets(1).Copy After:=wb.Sheets(1)
End If
End Sub