尝试让宏在多个工作表中执行相同的功能,我想我可以使用这种代码来选择我想要的数据:
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
我一直受到好消息的影响。 happytime"运行时错误' 13':类型不匹配"。
我是否尝试做变种不会做的事情?有没有办法做到这一点,我还没有学到呢?我已经好好地环顾了一下,并且发现了很多东西。谢谢你的帮助!
答案 0 :(得分:1)
您应该更改您的代码,使其像这样。您不能将变量设置为多个值,但可以使用检查多个值的条件。
不是最简单的方式,但它会起作用。
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
答案 1 :(得分:0)
在回应您对matrixugly提供的答案的评论时,您可以在子例程的顶部维护一个布尔变量。如果您需要添加或删除案例,可以在那里进行管理。
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
你也可以在一个单独的函数中进行检查,并在那里保持任何更改。
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
答案 2 :(得分:0)
您的代码非常接近,您需要将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