2016-12-06 17 views
0

我已經stucked今天這個上...錯誤5使用迪爾 - 宏複製從另一個工作簿片,採用SHEETNAME

我有幾個的.xlsx文件的文件夾名爲「文件修改」 例如,它們中的每一個都具有名爲specificaly的第一個表單,如「test1」。

我有其他的.xlsx文件的文件夾名爲「老文件中插入」 每個這些被稱爲特別是這樣的:「老test1.xlsx」,老TEST2,等...

我想我的宏將通過第一個文件夾和文件,並將相應的舊.xlsx的第一張表複製到另一個文件夾中。

該代碼遠沒有工作,但主要問題是,我得到一個錯誤5在Dir線,我認爲這是因爲我使用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

Dir是一個函數,你不能像'='那樣設置它,檢查你的將它轉換成'FileName = Dir(Pathname&「* .xlsx」,vbNormal)'' - 它具有工作所需的參數。 – Sgdva

+0

感謝您的幫助:) –

回答

1

如您所料,同時使用Dir在兩個不同的地方是自找麻煩。

在sub 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 
+0

你好ASH。謝謝,這很聰明,做了這份工作!有一個很好的 –

相關問題