Sub LoopThroughFiles()
StrFile = Dir("C:\Users\A9900899\Desktop\Desmond\VBAProject\Raw\")
While StrFile <> ""
Debug.Print StrFile & "Entering"
If StrFile Like "*xls*" Then 'check that current file is excel
Select Case True
'1
Case (StrFile Like "*Hong Kong*")
newSheetName = "Honggg"
Call searchThroughWorkBook(wb, sPath, StrFile, newSheetName)
'2
Case (StrFile Like "*London*")
newSheetName = "Londonnn"
Call searchThroughWorkBook(wb, sPath, StrFile, newSheetName)
Case Else
Debug.Print "Nope!!!"
End Select
End If
StrFile = Dir
Debug.Print StrFile & " Just before i exit, i am going to search for next"
Wend
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Function searchThroughWorkBook(ByRef wb As Workbook, ByVal sPath As String, ByVal StrFile As String, ByVal newSheetName As String)
' Set wb = Workbooks.Open(sPath & StrFile)
For Each wsSource In wb.Sheets
Debug.Print wsSource.name ' Check sheet name for something you want
If wsSource.name = "USD Bal Input" Then
Set wbTarget = Workbooks.Open("C:\Users\A9900899\Desktop\Desmond\VBAProject\Test2.xlsx")
If Dir(targetPath & "USDReport.xlsx") <> "" Then
Set wbTarget = Workbooks.Open("C:\Users\A9900899\Desktop\Desmond\VBAProject\USDReport.xlsx")
Else
'Create workbook if dont exist
AddNewWorkbook ("USDReport")
Set wbTarget = Workbooks.Open(targetPath & "USDReport")
'Call openWorkBookDialog
End If
wbTarget.Close SaveChanges:=True
Exit For
End If
Next wsSource
wb.Close False ' close workbook and don't save changes
End Function
我使用StrFile = Dir(“C:\ Users \ A9900899 \ Desktop \ Desmond \ VBAProject \ Raw \”)来获取该文件夹中的文件并循环浏览它们以执行某些操作。如果文件中包含单词hong kong,我会进入函数来做一些事情。但是,当我退出时,它返回一个空字符串,而不是包含文件夹中下一个文件的StrFile = Dir。文件夹中有更多文件。为什么会这样?这与Dir的工作方式或某些范围问题有关吗?请帮助谢谢