以你的代碼是,你可以在下面的if語句添加到對於每個迴路:
For Each f1 In ff
If StrComp(f1.Name, ActiveWorkbook.Name, vbTextCompare) <> 0 And _
InStr(1, f1.Name, "~") = 0 Then
Set SrcBook = Workbooks.Open(f1)
Range("A2:IV" & Range("A20").End(xlUp).Row).Copy
ThisWorkbook.Worksheets(1).Activate
Range("A20").End(xlUp).Offset(1, 0).PasteSpecial
Application.CutCopyMode = False
SrcBook.Close
End If
Next
第一個條件防止打開當前文件本身,第二個條件也跳過Excel在打開文件時創建的臨時文件。
返工代碼
正如順便說一句,我會重構和擴大代碼如下:
Sub Auto_Open()
On Error GoTo Err_
Dim fso As Object
Dim Folder As Object
Dim Files As Object
Dim File As Object
Application.ScreenUpdating = False
Set fso = CreateObject("Scripting.FileSystemObject")
Set Folder = fso.Getfolder("C:\Temp\Excel")
Set Files = Folder.Files
For Each File In Files
If StrComp(File.Name, ActiveWorkbook.Name, vbTextCompare) <> 0 And _
InStr(1, File.Name, "~") = 0 Then
With Workbooks.Open(File.Path)
Range("A2:IV" & Range("A20").End(xlUp).Row).Copy
ThisWorkbook.Worksheets(1).Activate
Range("A20").End(xlUp).Offset(1, 0).PasteSpecial
Application.CutCopyMode = False
.Close
End With
End If
Next
Exit_:
Application.ScreenUpdating = True
Set Files = Nothing
Set Folder = Nothing
Set fso = Nothing
Exit Sub
Err_:
Resume Exit_
End Sub
一個幾句話:
- 錯誤處理確保即使在出現錯誤的情況下
ScreenUpdating
是再次切回。否則,如果發生錯誤,您可能會讓應用程序無法刷新給用戶。
- 每個變量的分隔線 - 易於掌握
- 更明確的變量名稱。首先,代碼應該是容易閱讀,不容易打字。
With
-block爲局部變量使其作用域顯式。保存本地變量SrcBook。
在這裏可能會爭辯說,該變量的名稱有助於理解問題,應該更好地保留。
- 顯式設置對象變量爲
Nothing
。可能是偏執狂,但作爲SOP,在某些情況下,它可以幫助避免所有類型的奇怪問題。
,因爲它可能是具有挑戰性的獲得在With
- 阻塞代碼的意圖,我會走得更遠,並提取塊到一個新的方法有意向揭示的名字讓事情更清晰。該名稱可以沿着CopyProductListFromFile
。
如果你想感謝某人,因爲他們的答案奏效,你可以在他們的答案和/或投票旁邊勾選checkmatrk。查看幫助中心[Someone answers](http://stackoverflow.com/help/someone-answers) – rene 2014-12-04 08:10:01