【问题标题】:InStr for array of values (Possible?)InStr 用于值数组(可能吗?)
【发布时间】:2017-05-04 13:18:28
【问题描述】:
Private Sub Workbook_Open()

Dim WBname As String
WBname = ThisWorkbook.name

If Not InStr(WBname, "test") > 0 Then
    MsgBox ("NotOK")
End If

End Sub

编辑:更多说明。

我现在测试“测试”是否在工作簿名称中。

但我想测试工作簿名称中是否有比“测试”更多的词,而无需将代码复制粘贴一千次。

【问题讨论】:

  • 您可以使用 Range.Find 查看字符串是否在工作表上。或者您可以使用 Join() 将数组连接成一个字符串,您可以使用 Instr 从中进行检查。我相信 Range.Find 方法会更快。
  • 未在电子表格中定义的完整字符串列表。 - 您是说需要测试一个(或多个)几个独立字符串值是否在工作簿名称? 电子表格中未定义是什么意思?
  • 澄清了帖子。对不起。
  • 阅读编辑似乎要测试工作表名称是否包含测试。我建议您遍历 thisworkbook.worksheets,如果您想根据名称测试一组值,然后将它们放入一个数组并执行嵌套循环。
  • 我一直在看这个并且一直想知道If Not。是不是有很多单词要检查(例如“Test”)并且您必须在 Workbook 名称中包含其中一个?就目前而言,如果工作簿名称不包含“Test”,您将收到“NotOK”消息框。

标签: excel vba


【解决方案1】:

如果WBname 必须包含所有单词,请使用此选项

Dim WBname As String
WBname = ThisWorkbook.Name

Dim arrWords As Variant, aWord As Variant
arrWords = Array("aa", "bb", "cc") 'input your words list here

For Each aWord In arrWords
    If Not InStr(WBname, aWord) > 0 Then
        MsgBox ("NotOK")
        Exit For
    End If
Next

如果WBname 必须包含至少一个单词,请使用此选项

Dim WBname As String
WBname = ThisWorkbook.Name

Dim arrWords As Variant, aWord As Variant
arrWords = Array("aa", "bb", "cc") 'input your words list here

Dim wordFound As Boolean
wordFound = False
For Each aWord In arrWords
    If InStr(WBname, aWord) > 0 Then
        wordFound = True
        Exit For
    End If
Next
If Not wordFound Then
    MsgBox ("NotOK")
End If

【讨论】:

    【解决方案2】:

    您可以在 IF 中使用 AND:

    If Not InStr(WBname, "test") > 0 and not InStr(WBname, "other word") ...
    

    或者您可以使用 OR,具体取决于您的测试。

    【讨论】:

    • 我觉得没有错。但也许 OP 有超过 2 或 3 个单词要测试,这使得这种方法有点麻烦。我认为这就是 OP 对“无需复制粘贴代码一千次”的含义。也许这就是它被否决的原因。不要个人认为。
    • 感谢您的回答。不!!我个人不接受!!就我而言,我认为 bubububub 不想多次复制相同的“if...end if”,所以这是我必须使用运算符 AND 或 OR..
    【解决方案3】:

    使用 Excel 公式的方法更短、更慢:

    containsAny = Evaluate("count(search({""ab"",""cd""},""bcde""))>0") ' True
    

    或与您的样品:

    Private Sub Workbook_Open()
        If Evaluate("count(search({""test"",""Book1""},""" & Me.Name & """))=0") Then
            MsgBox "NotOK"
        End If
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      相关资源
      最近更新 更多