2016-09-13 5 views
0

VBAコードを取得して、列のどのセルに「イベント」が含まれているかを教えています。スプレッドシートには、セル(3,2)にイベントがあり、その後に12番目の行(セル(15,2);セル(27,2);セル(39,2)など)があります。配列からのイベントを含むセルの選択VBA

イベント名を定義する配列を作成しました。これらの値のいずれかを1つずつ保持するセルを選択したいと思います。

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 

私はこれが非常に簡単だと確信していますが、今日は何も起こっていません。

+2

なぜなら、 '.Value'の代わりに' .Text'を使う理由はありますか? '.Text'はセルの値ではなく、表示されるテキストです(例:列が狭すぎる場合は" #### ") – arcadeprecinct

答えて

0

あなたはセルの値が配列の要素であるかどうかを確認したい場合は、全体の配列をループしており、それに対してそれぞれの値をチェックするので、このような何か:あなたが必要な場合は

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 
+0

ありがとう!私はそれが何かシンプルなことを知っていた、その場でVBAを学ぶことは常に楽しいです。 – Andrew

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 
関連する問題