数组数组中的string给出错误
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”。 所以arrays(“9811,7849”)给了我不正确的结果。任何想法如何使其正确工作?
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)
Array("9811,7849")
是一个包含一个String
元素的数组: "9811,7849"
Array(9811,7849)
是一个包含两个元素的数组: 9811
和7849
你应该看看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