【问题标题】:Problem with Scripting.FileSystemObject and INSTR and IF THEN in VBA codeVBA 代码中 Scripting.FileSystemObject 和 INSTR 和 IF THEN 的问题
【发布时间】:2021-09-09 14:54:22
【问题描述】:

我不明白为什么这不起作用

xSource = vrtSelectedItem  '<<== C:\Users\Me\Desktop\Document01.pdf

Set FSO = VBA.CreateObject("Scripting.FileSystemObject")
    
If Not InStr(xSource, ".jpg") Or Not InStr(xSource, ".bmp") Or Not InStr(xSource, ".png") _
Or Not InStr(xSource, ".tif") Or Not InStr(xSource, ".tga") Or Not InStr(xSource, ".jpeg") _
Or Not InStr(xSource, ".doc") Or Not InStr(xSource, ".pdf") Or Not InStr(xSource, ".rtf") _
Or Not InStr(xSource, ".htm") Or Not InStr(xSource, ".html") Or Not InStr(xSource, ".txt") _
Or Not InStr(xSource, ".docx") Or Not InStr(xSource, ".tdm") Or Not InStr(xSource, ".wri") _
Or Not InStr(xSource, ".xls") Or Not InStr(xSource, ".xlsx") Or Not InStr(xSource, ".xlsm") _
Or Not InStr(xSource, ".ods") Or Not InStr(xSource, ".odt") Then

MsgBox "File type not allowed"
Exit Sub

Else

.....

虽然文件包含 .pdf,但我得到 MsgBox "File type not allowed"!我列出的所有其他文件类型也会发生这种情况,实际上将它们从错误消息中排除!谁能给我一些建议?谢谢

【问题讨论】:

  • 接受的答案是 100% OK,但是您的逻辑失败还有另一个原因:您应该在比较中使用 AND,而不是 OR。也许这是最容易看到的等式:NOT a OR NOT b == NOT (a AND b),在您的情况下,(a AND b) 将始终为 FALSE,并且将始终打印消息。

标签: excel vba string syntax-error instr


【解决方案1】:

TL;DRInStr 不返回 Boolean,而是返回 Variant (Long),指定第一个的 位置一个字符串出现在另一个字符串中。


简化解释问题:

xSource = "C:\Users\Me\Desktop\Document01.pdf"

Debug.Print InStr(xSource, "pdf")
Debug.Print Not InStr(xSource, "pdf")
Debug.Print CBool(Not InStr(xSource, "pdf"))

返回

 32 
-33 
True

InStr 不返回布尔值,而是返回一个字符串在另一个字符串中第一次出现的位置。通常不使用Not,而是检查InStr 的结果是否为&gt; 0,以确定是否找到匹配项。

在数值表达式上使用Not 会执行按位求反,如上所示,这会导致匹配结果最终计算为True。事实上,没有匹配计算为TrueCBool(Not(0)) 返回True)。

这是另一种方法:

Private Function IsValidFileType(ByVal filePath As String) As Boolean
    Dim FSO As Scripting.FileSystemObject
    Set FSO = New Scripting.FileSystemObject
    
    Dim extension As String
    extension = FSO.GetExtensionName(filePath)

    Select Case extension
        Case "jpg", "bmp", "png" '< and so on
            IsValidFileType = True
        Case Else
            IsValidFileType = False
    End Select
End Function

【讨论】:

  • 太棒了。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2013-12-29
  • 1970-01-01
  • 2015-07-03
  • 1970-01-01
  • 2014-03-27
  • 2015-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多