2017-07-06 72 views
0

我有這樣的代碼:VBA - 設定一個數值數組,並將其與細胞

Sub PipelineStatusConvert() 

Dim rng1 As Range 
Dim tgt As Range 
Dim ws As Worksheet 
Dim cell As Object 
Dim myarray As Variant 
myarray = Array("1", "2", "3") '4, 5, 6, 7, 8, 9) 

Set ws = ActiveWorkbook.ActiveSheet 
Set rng1 = ws.Range("K13:K1000") 

' If Intersect(ActiveCell, rng1) Is Nothing Then 
' 
'  MsgBox "The active cell does NOT Intersect " & rng1.Address 
' 
' Else 
' 
'  MsgBox "The active cell does Intersect " & rng1.Address 
' 
' End If 

For Each cell In rng1 

'evaluate something 

    If cell <> myarray Then 
    MsgBox "no intersection" 
' MsgBox cell.Address 
    End If 

' Select Case 
    ' Case 1 

Next cell 

End Sub 

我試圖運行範圍內選擇的每一個細胞的檢查,並說,如果單元格的值不數組(1-3),然後

在做某些事情..

我一直運行到‘類型不匹配錯誤’。我知道它與數組聲明有關,因爲我認爲它試圖將單元格值與數組進行比較(這不起作用)。

我該如何重新設計這個?

感謝

回答

0

你需要寫一個函數來搜索值的數組。稍微修改你的代碼,我想出了以下內容:

Sub PipelineStatusConvert() 
    Dim rng1 As Range 
    Dim tgt As Range 
    Dim ws As Worksheet 
    Dim cell As Range 
    Dim myarray As Variant 

    myarray = Array("1", "2", "3") '4, 5, 6, 7, 8, 9) 

    Set ws = ActiveWorkbook.ActiveSheet 
    Set rng1 = ws.Range("K13:K1000") 

    For Each cell In rng1 
     If Not isInArray(cell.Value, myarray) Then 
      MsgBox "no intersection" 
     End If 
    Next 
End Sub 

Function isInArray(Match As String, SourceArray As Variant) As Boolean 
    isInArray = (UBound(Filter(SourceArray, Match)) > -1) 
End Function 
+0

謝謝你,我會把它放在後面的口袋裏。我實際上能夠用LIKE運算符和通配符解決這個問題! –