请帮助需要你的帮助,
说明
我设计了一个VBA代码,我希望将一个字符串与目录中的FileName进行比较。在这种情况下,我使用了Instr函数,这只能帮助我3个案例,但不是动态的。
阐释:
如果str = 4567并且与filename相符,其中filename可以是:
1.xs1234567.pdf
2.4567.pdf
3.4567(1).PDF
4.更新4567(2).pdf
所以我创建的代码有助于查找所有文件,但这不正确。它应排除第一个文件名,即:xs1234567.pdf
以下代码:
Dirfname = finDir
fName = Mid((Dirfname), 1, (InStr(1, (Dirfname), ".") - 1))
fileExt = Mid((Dirfname), (InStr(1, (Dirfname), ".") + 1), 3)
**If (InStr(1, fName, wkvalue) > 0 And wkvalue <> "") Then ** 'checking lookup val in instr
If (Trim(UCase(fileExt)) = "PDF" Or Trim(UCase(fileExt)) = "TIF") Then
Cells(recnum, 2).Value = "Yes"
'col = col + 1
ws.Hyperlinks.Add Anchor:=Cells(recnum, (col + 1)), _
Address:=SourceFolderName & "\" & Dirfname
col = col + 1
'Else: Cells(recnum, 2).Value = "No"
End If
End If
请告知可以为此案件做些什么。
答案 0 :(得分:2)
您可以使用正则表达式来帮助您。我不是很熟练,但这是一个相对简单的案例。这是一个改编自tmehta.com/regexp的函数,您可以将其与文件夹中文件名的迭代结合使用:
Function RegExpFind(FindIn, FindWhat As String, _
Optional IgnoreCase As Boolean = False) As Variant
Dim i As Long
Dim rslt() As String
'// Using Late Binding here, use the commented types if you've added
'// the "Microsoft VBScript Regular Expressions" reference
Dim RE As Object 'RegExp
Dim allMatches As Object 'MatchCollection
Dim aMatch As Object 'Match
'// Use "Set RE = New RegExp" if using the VBScript reference
Set RE = CreateObject("vbscript.regexp")
RE.Pattern = FindWhat
RE.IgnoreCase = IgnoreCase
RE.Global = True
Set allMatches = RE.Execute(FindIn)
'// check if we've found anything, if not return a single element array
'// containing an empty string. If we've found something return at least
'// at least a single element array containing the matched expressions
If allMatches.Count = 0 Then
ReDim rslt(0 To 0)
rslt(0) = ""
Else
ReDim rslt(0 To allMatches.Count - 1)
For i = 0 To allMatches.Count - 1
rslt(i) = allMatches(i).Value
Next i
End If
RegExpFind = rslt
End Function
您需要在FindIn
参数中传递文件名作为"^4567"
参数和正则表达式模式FindWhat
。只有当它出现在搜索字符串的开头时,这种方式才会返回4567
(作为返回数组中的第一个元素)。如果需要,此功能可以很容易地回收用于其他搜索。
答案 1 :(得分:1)
假设您的匹配条件是4567之前的字符(如果有)是空格
i = InStr(1, fName, wkvalue)
if i > 0 and wkvalue <> "" Then
ch = " "
if i > 1 then
ch = mid(fName, i - 1, 1)
end if
if ch = " " then
...
答案 2 :(得分:1)
您没有描述为什么应该拒绝第一个文件名,但我认为这是因为它在wkvalue
之前和/或之后有一个数字(0-9),这样“4567”不是整个数字。在这种情况下,这将起作用:
charBefore = ""
charAfter = ""
pos = InStr(fName(i), wkvalue)
If pos = 1 Then
' It's at the beginning of the filename.
' Get character after the number.
charAfter = Mid(fName(i), pos + Len(wkvalue), 1)
ElseIf pos > 1 Then
' It's not at the beginning of the filename
' Get characters before and after the number.
charBefore = Mid(fName(i), pos - 1, 1)
charAfter = Mid(fName(i), pos + Len(wkvalue), 1)
Else
' Number not found.
End If
' Could add another ElseIf to check if it's at the end of the filename.
If pos > 0 And wkvalue <> "" _
And Not charBefore Like "#" And Not charAfter Like "#" Then
' Number found and not preceded or followed by a digit (0-9).
' Do your thing.
End If