设置一个variables有多个可能的值

试图让一个macros在多个表中执行相同的function,我想我可以使用这种代码来select我想要的数据:

Sub Foo Dim OtherStuff As Things Dim Thing1 as Variant Thing1 = "a" Or "b" Or "c" 'more things If cell.value = Thing1 Then Do stuff End If Next Cell End Sub 

我不断碰到良好的“快乐时光”运行时错误“13”:types不匹配“。

我是否试图做一些变体不会做的事情? 有没有办法做到这一点,我只是没有学到呢? 我环顾四周,并没有find太多东西。 谢谢您的帮助!

你的代码非常接近,你需要Thing1作为一个数组(你已经正确地将它定义为一个变体)。 然后,你只要循环的元素。

这是修改的代码。 很简单,但如果您有任何问题,请回复:

 Sub Foo() 'Dim OtherStuff As things Dim Thing1 As Variant, Cell As Range Thing1 = Array("a", "b", "c") 'more things For Each Cell In Range("A1:A10") For Each Thing In Thing1 If Cell.Value = Thing Then 'Do stuff End If Next Thing Next Cell End Sub 

你应该改变你的代码,所以这是这样的。 您不能将variables设置为多个值,但可以有一个条件来检查多个值。

不是最清楚的方式,但它会工作。

 Sub Foo Dim OtherStuff As Things Dim Thing1 as Variant ' won't work -> Thing1 = "a" Or "b" Or "c" 'more things 'this should work If cell.value = "a" Or cell.value = "b" cell.value = "c" Then Do stuff End If Next Cell End Sub 

为了回应你对matrix提供的答案的评论,你可以在子程序的顶部维护一个布尔variables。 如果您需要添加或删除案例,您可以在那里pipe理它。

 Sub Foo() Dim valueMatches As Boolean valueMatches = cell.value = "a" Or _ cell.value = "b" Or _ cell.value = "c" ' ...more code... If valueMatches Then ' Do stuff End If End Sub 

您也可以在单独的function中进行检查,并在那里保持任何更改。

 Private Function ValueMatches(ByVal value As String) As Boolean ' Maintain values to match in this single function. ' Note: Function will need to be public instead of ' private if stored in another module. ValueMatches = value = "a" Or value = "b" Or value = "c" End Function Sub Foo() ' ...more code... If ValueMatches(cell.value) Then ' Do stuff End If End Sub