我努力做到以下幾點:Excel的VBA遍歷,文件 - 死循環
- 通過的所有文件指定一個文件夾(containinf * .XLSM文件)
- 迭代
- 每個開放文件,運行宏,關閉和文件
- 移動保存到一個文件,直到所有已經完成。
下面的代碼工作,但循環永遠不會結束......它好像每次我保存剛剛處理過的文件時,它都會顯示爲要通過的文件列表中的新項目。
我在做什麼錯?
謝謝。
Sub runMe()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim MyPath As String
Dim wb As Workbook
Dim myDir As String
With Application
.ScreenUpdating = False
.DisplayAlerts = False
.EnableEvents = False
End With
myDir = "\templates"
Debug.Print ActiveWorkbook.Path
MyPath = ActiveWorkbook.Path & myDir
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object associated with the directory
Set objFolder = objFSO.GetFolder(MyPath)
'Loop through the Files
For Each objFile In objFolder.Files
If InStr(objFile.Name, "~") = 0 And InStr(objFile.Name, ".xlsm") <> 0 Then
Set wb = Workbooks.Open(objFile, 3)
Application.Run "'" & wb.Name & "'!doMacro"
wb.Close SaveChanges:=True
' Gets stuck in this loop
' WHY DOES IT KEEP LOOPING?
End If
Next
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.EnableEvents = True
End With
End Sub
您的代碼似乎罰款。你在doMacro部分做了什麼?它以某種方式影響文件?這樣 – varocarbas
問題最容易通過設置一個斷點,並通過線通過代碼行步,當您去檢查變量追查。這不是複雜的代碼,所以這應該是幾分鐘的時間來調試。 – Tomalak
這可能不會解決您的問題,而是'Workbooks.Open'需要一個'String'作爲第一個參數(或一些可以轉換爲'String')。 – Ioannis