我有一些叫做Team-(随机数).txt的文件。
Dir("Team-" & "*" & ".txt")
但是当有变化的时候,可能会出现名为Team-(随机数)-AAA.txt,Team-(随机数)-AAB.txt的文本文件,但最近的文件总是被称为Team-(Random)数).TXT。
由于Dir只返回1个文件并且随机执行此操作是否有办法获取文件Team-(随机数).txt?
如果dir以正常顺序返回结果应该没问题,但显然它是随机的。
我想过要排除-AAA部分,但不知道语法应该是什么。或者以一种不太有效的方式获取所有文件并将其排序在一个数组中,但是使用10 - 200个文件它并不是非常有效。
现在我希望可以给我一些语法,为我的问题排除部分或其他解决方法,谢谢!
答案 0 :(得分:3)
我会说正则表达式。
Private Sub TeamTxtExists()
Dim Path As String, Pattern As String, FileFound As String
Dim REGEX As Object, Matches As Object
Dim oFSO As Object, oFolder As Object, oFile As Object
Path = "D:\Personal\Stack Overflow\" 'Modify as necessary.
Pattern = "(Team-(\d+).txt)"
Set REGEX = CreateObject("VBScript.RegExp")
With REGEX
.Pattern = Pattern
.Global = True
.IgnoreCase = True
End With
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(Path)
For Each oFile In oFolder.Files
Set Matches = REGEX.Execute(oFile.Name)
For Each Match In Matches
Debug.Print Match.Value
Next Match
Next oFile
End Sub
这将在您的即时窗口(VBE中的Ctrl-G)中打印文件名中没有AAA
等文本文件的所有名称。经过试验和测试。
答案 1 :(得分:2)
与Loop through files in a folder using VBA?
类似Dir
有效查找与 team-xxxx.txt相匹配的第一组文件 Like
进行简单匹配Regexp
进行更难的比赛Dir
列表我选择了正则表达式。
<强>码强>
Sub LoopThroughFiles()
Dim objRegex As Object
Dim StrFile As String
Dim bFound As Boolean
bFound = False
Set objRegex = CreateObject("VBScript.RegExp")
objRegex.Pattern = "team-\d+"
StrFile = Dir("c:\temp\team-*.txt")
Do While Len(StrFile) > 0
If objRegex.test(StrFile) = False Then
StrFile = Dir
Else
bFound = True
MsgBox "Your file is " & StrFile
Exit Do
End If
Loop
If Not bFound Then MsgBox "No Match", vbCritical
End Sub
答案 2 :(得分:0)
这有帮助吗?:
Dir("Your_folder_path_ending_with_a_\" & "Team-(*).txt")
进一步深入并使用图片中显示的文件夹内容:
此子句将返回仅包含“Team-(Random Number).txt”的所有文件名:
Sub showFileName()
Dim FolderPath As String: FolderPath = "C:\test\"
Dim Filter As String: Filter = "Team-(*).txt"
Dim dirTmp As String
dirTmp = Dir(FolderPath & Filter)
Do While Len(dirTmp) > 0
Debug.Print dirTmp
dirTmp = Dir
Loop
End Sub
结果是:
Team-(123)的.txt
Team-(14)的.txt
Team-(PI)的.txt