[英]Dir Function in Excel 2010 VBA not working
我試圖遍歷給定目錄以找到最新下載的csv文件。 由於某種原因,即使該文件確實存在,我的Dir函數也找不到任何文件。 我對VBA並不完全熟悉,因此我可能會缺少某種執行Dir功能的參考,但是我找不到任何可以告訴我的網上信息。 所有示例和論壇都像我一樣使用Dir,但是我無法工作。 這是代碼,請告訴我您是否可以看到我在做錯什么:
Public Function Get_File() as string
Dim filePath As String
ChDir ("..")
filePath = CurDir
'Goes back to Documents directory to be in same directory as macro
ChDir (filePath & "\Documents")
filePath = filePath & "\Downloads\test.txt"
filePath = getLatestFile(filePath)
Get_File = filePath
End Function
Public Function getLatestFile(pathToFile As String) As String
Dim StrFile As String
Dim lastMod As Variant
Dim nextMod As Variant
Dim lastFileName As String
StrFile = Dir(pathToFile)
lastFileName = StrFile
lastMod = FileDateTime(StrFile)
While Len(StrFile) > 0
Debug.Print StrFile
StrFile = Dir
nextMod = FileDateTime(StrFile)
If nextMod > lastMod Then
lastFileName = StrFile
lastMod = nextMod
End If
Wend
getLatestFile = lastFileName
End Function
test.txt文件位於我的下載文件中,並且將filePath字符串打印為正確的路徑,但是我不斷收到一條錯誤消息,指出它找不到該文件。 第一次使用Dir(pathToFile)時失敗。 任何幫助將不勝感激。
Dir()
僅返回路徑的文件名部分,即不返回文件夾部分。 例如,
Dir("C:\MyPath\MyFile.txt")
返回MyFile.txt
而不是C:\\MyPath\\MyFile.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.