数组中的字符串给出错误

时间:2015-05-28 18:38:42

标签: excel vba excel-vba

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”。所以Array(“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)

1 个答案:

答案 0 :(得分: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