我想浏览文件列表并打开一个特定的文件。 我有以下情况:
Dim f2 As Object
If f2 Like "*DT*" Then....
我想添加第二个条件:如果名称中包含字符*+*
,*&*
或*to*
,它将跳过文件。
然后我会得到类似的东西:
If f2 Like "*DT*" And Not "*+*, *&*, *to*" Then....
所以说我有以下两个文件:
List DT Q2 2018
List DT Q2 to Q3 2018
我的代码应该只打开第一个文件。
答案 0 :(得分:1)
如果我对您的理解正确,那么您将要测试像这样的文件名
Option Explicit
Function openIt(inp As String) As Boolean
openIt = False
If inp Like "*DT*" Then
If inp Like "*+*" Or inp Like "*&*" Or inp Like "*to*" Then
Else
openIt = True
End If
End If
End Function
Sub testIt()
Dim fname As String
fname = "List DT Q2 2018"
'fname = "List DT Q2 to Q3 2018"
If openIt(fname) Then
Debug.Print "Open " & fname
Else
Debug.Print "No need to open " & fname
End If
End Sub
答案 1 :(得分:1)
尝试以下
If f2 Like "*DT*" And ((Not (f2 Like "*to*")) And (Not (f2 Like "*&*")) And (Not (f2 Like "*+*"))) Then
答案 2 :(得分:1)
以防万一您没有足够的答案,这里还有一个:)
我选择使用InStr()
函数来检查要排除的字符。
Sub LoopFiles()
Dim path As String
path = "C:\Users\Public\Documents\"
Dim file2 As String
file2 = Dir(path & "*.xls*")
Do While Len(file2) > 0
If InStr(file2, "DT") > 0 And Not (InStr(file2, "+") > 0 Or InStr(file2, "&") > 0 Or InStr(file2, "to") > 0) Then
Workbooks.Open (path & file2)
End If
file2 = Dir 'moves on to the next file
Loop
End Sub