2015-05-28 37 views
1
Sub highlight() 
    Dim w As Workbook 
    Dim sh As Worksheet 
    Dim x As Integer 
    Dim rn As Range 
    Dim k As Long 
    Dim number As Variant 

    number = Array(9811, 7849) 


    Set w = ThisWorkbook 


    Set sh = w.Worksheets("Sheet1") 
    sh.Select 
    Cells.Find("hello").Select 
    ActiveCell.Offset(1, 0).Select 
    Set rn = sh.UsedRange 
    k = rn.Rows.Count + rn.Row - 1 
    For x = 1 To k 
     For j = 0 To UBound(number) 
     If ActiveCell.Value <> number(j) Then 
      Selection.Interior.Color = vbYellow 
     Else 
      Selection.Interior.ColorIndex = xlNone 
      Exit For 
     End If 

     Next j 
     ActiveCell.Offset(1, 0).Select 'moves activecell down one row. 
    Next x 

End Sub 

上面的代碼工作得很好。
現在,當我從我的GUI發送相同的數字(9811,7849)到下面的vba代碼時,它們被存儲爲phm =「9811,7849」。所以陣列(「9811,7849」)給了我不正確result.Any想法如何使它正常工作\數組中的字符串給出錯誤

sub highlight(phm as variant) 
Dim w As Workbook 
Dim sh As Worksheet 
Dim x As Integer 
Dim rn As Range 
Dim k As Long 
Dim number As Variant 


number = Array(phm) 
+0

這是不可讀。修正你的縮進,解釋你的代碼,解釋什麼結果是不正確的。 – Amit

+0

縮進是正確的..我已經發布了兩個代碼。第一個是我已經嘗試過的,第二個是我想要的 –

+0

不正確意味着所有的單元格都被突出顯示,而不是錯誤的單元格。我知道錯誤是因爲:number = Array(「9811,7849」)。我無法修復它 –

回答

2

Array("9811,7849")是一個String元素的數組:"9811,7849"

而且Array(9811,7849)是一個數組有兩個元素:98117849

你應該看看Split()功能

number=Split(phm,",") 

如果你需要number爲整數,也CInt()適用於:

Dim number() As Integer 
phm=Split("9811,7849",",") 
ReDim number(LBound(phm) To UBound(phm)) As Integer 
For i=LBound(phm) To UBound(phm) 
    number(i)=CInt(phm(i)) 
Next i 

編輯

您要求在評論這個片段添加到您的子程序:

Sub highlight(ByVal phm As String) 
    Dim w As Workbook 
    Dim sh As Worksheet 
    Dim x As Integer 
    Dim rn As Range 
    Dim k As Long 
    Dim number() As String 


    number = Split(phm, ",") 


    Set w = ThisWorkbook 


    Set sh = w.Worksheets("Sheet1") 
    sh.Select 
    Cells.Find("hello").Select 
    ActiveCell.Offset(1, 0).Select 
    Set rn = sh.UsedRange 
    k = rn.Rows.Count + rn.Row - 1 
    For x = 1 To k 
     For j = 0 To UBound(number) 
     If ActiveCell.Value <> number(j) Then 
      Selection.Interior.Color = vbYellow 
     Else 
      Selection.Interior.ColorIndex = xlNone 
      Exit For 
     End If 

     Next j 
     ActiveCell.Offset(1, 0).Select 'moves activecell down one row. 
    Next x 

End Sub 
+0

你可以請你的代碼在我的第一個代碼? –

+0

當然可以..... –

+0

完美的作品!謝謝:) –