我试图让我的VBA代码告诉我列中的哪些单元格包含“事件”。电子表格在单元格(3,2)中有一个事件,然后在那之后每隔12行(单元格(15,2);单元格(27,2);单元格(39,2);等等)。
我创建了一个数组来定义事件名称,我想逐个选择包含任何值的单元格。
Dim eventsArray(3) As String
eventsArray(0) = "W"
eventsArray(1) = "X"
eventsArray(2) = "Y"
eventsArray(3) = "Z"
Dim eventRow As Range
For i = 1 To maxRow 'my maxRow was already defined properly
eventRow = Cells(i, 2)
If eventRow.Text = eventsArray Then
eventRow = Cells(i + 1, 2)
End If
MsgBox (eventRow)
Next i
我确信这非常简单,今天没有任何事情发生。
答案 0 :(得分:0)
如果要检查Cell Value是否是数组的元素,则必须遍历整个数组并检查每个值,如下所示:
Dim i As Integer
Dim eventsArray(3) As String
Dim arrayElem As Variant 'Variable for looping the Array(needs to be Variant)
eventsArray(0) = "W"
eventsArray(1) = "X"
eventsArray(2) = "Y"
eventsArray(3) = "Z"
Dim eventRow As Range
For i = 1 To maxRow
Set eventRow = Cells(i, 2) 'Set current cell to the range variable
For Each arrayElem In eventsArray 'Loop through the array
If eventRow.Value = arrayElem Then 'If the Value matches with an item in the array
MsgBox Cells(i + 1, 2).Address 'MsgBox with cell address
End If
Next arrayElem
Next i
答案 1 :(得分:0)
如果您需要反复测试某个值是否在一个集合中,Scripting.Dictionary可能会为您提供最佳性能:
'You need to add a reference to Microsoft Scripting Runtime.
Dim events As New Scripting.Dictionary
events.Add "W", vbNull
events.Add "X", vbNull
events.Add "Y", vbNull
events.Add "Z", vbNull
Dim eventRow As Range
For i = 1 To maxRow 'my maxRow was already defined properly
eventRow = Cells(i, 2)
If events.Exists(eventRow.Value) Then
eventRow = Cells(i + 1, 2)
End If
MsgBox eventRow
Next i