返回文件名通配符的值

我试图围绕interwebz进行研究,但无济于事。

我有这个代码来search文件夹来查看文件是否存在。 问题是我不知道完整的文件名,所以我用通配符。 带有通配符“Provider * _extra”&“。csv”的文件 – 通配符表示date和string – 例如Provider_20131126_purple_extra.csv。

我想知道通配符的价值是什么 – 例如,我想调用“20131126_purple”或其他任何东西。 有谁知道如何在VBA中做到这一点? 先谢谢你。

FileName = Dir$(MyPath & "PROVIDER*_EXTRA" & ".csv") If (Len(FileName) > 0) Then wb1.Sheets("Found Files").Activate LastRow = Range("E" & Rows.Count).End(xlUp).Row + 1 Range("E" & LastRow).Activate ActiveCell = "PROVIDER EXTRA FILE" wb1.Sheets("Control").Activate Else End If 

您可以使用

Debug.print FileName获取当前正在使用的文件的名称。

如果你想遍历一个文件夹中的所有文件,请看看这个

短样本:

 Public Const PathToFolder As String = "C:\SampleFolder\" Sub PrintFilesNames() Dim file As String file = Dir$(PathToFolder) While (Len(file) > 0) Debug.Print file file = Dir Wend End Sub 

您可以使用REPLACEfunction来尝试:

 wildcard = Replace(FileName, "Provider", "") wildcard = Replace(wildcard, "_extra.csv", "") 

这将做你想要的。

我有这样的function,我写和使用的所有时间:

 Function GetFilenamesMatchingPattern(ByVal pathPattern As String, _ Optional attributes As VbFileAttribute = vbNormal) As String() Dim i As Long Dim nFiles As Long Dim filenames() As String nFiles = CountFilesMatchingPattern(pathPattern, attributes) If nFiles > 0 Then ReDim filenames(1 To nFiles) filenames(1) = dir(pathPattern, attributes) For i = 2 To nFiles filenames(i) = dir() Next i Else 'Return unallocated array End If GetFilenamesMatchingPattern = filenames End Function Function CountFilesMatchingPattern(ByVal pathPattern As String, _ Optional attributes As VbFileAttribute = vbNormal) As Long Dim nFiles As Long If dir(pathPattern, attributes) = "" Then nFiles = 0 Else nFiles = 1 Do While dir() <> "" nFiles = nFiles + 1 Loop End If CountFilesMatchingPattern = nFiles End Function 

道歉,如果有人不喜欢的风格!

通配符的示例用法:

 Dim filenames() As String filenames = GetFilenamesMatchingPattern("C:\Users\myName\Documents\Book*.xlsm") 'returns an array of Strings: '{"Book1.xlsm", "Book2.xlsm", "Book2_test.xlsm"} 

现在针对您的具体问题,即获取各种通配符值:

 Dim i As Long Dim filenames() As String Dim wildcardValues() As String Dim part1 As String Dim part2 As String part1 = "Book" ' yours would be "Provider_" part2 = ".xlsm" ' yours would be "_extra.csv" filenames = GetFilenamesMatchingPattern("C:\Users\myName\Documents\" _ & part1 & "*" & part2) ReDim wildcardValues(LBound(filenames) To UBound(filenames)) For i = LBound(filenames) To UBound(filenames) wildcardValues(i) = Replace(Replace(filenames(i), part1, ""), part2, "") Next i 'wildcardValues is now: '{"1", "2", "2_test"} 'Done.