文件名通配符的返回值

时间:2013-11-26 16:51:00

标签: excel vba wildcard

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

我有这个代码搜索文件夹以查看文件是否存在。问题是我不知道完整的文件名,所以我使用了通配符。带有通配符的文件" Provider * _extra"&" .csv" - 通配符表示日期和字符串 - 例如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

3 个答案:

答案 0 :(得分:2)

您可以使用REPLACE功能尝试:

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

答案 1 :(得分:2)

这将做你想要的。

我有这对函数,我一直在编写和使用:

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.

答案 2 :(得分:1)

你可以使用

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

如果您想循环浏览文件夹中的所有文件,请参阅this

简短样本:

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