类型不匹配将范围分配给1d数组

时间:2014-07-16 19:34:31

标签: vba excel-vba excel

我有一个包含值和数字的文本格式的范围。我试图只将数字分配给一个数组,然后我将文本值分配给另一个数组而不必循环遍历该范围。但是,这段代码说 - 类型不匹配?

  Sub Igra()
  Dim Arr() As Variant
  'convert the range values from text to general
  Sheets("Sheet1").Range("R32:W32").NumberFormat = "General"
  Sheets("Sheet1").Range("R32:W32").Value = Sheets("Sheet1").Range("R32:W32").Value
  ' assign only the numbers to the array
  Arr = Sheets("Sheet1").Range("R32:W32").SpecialCells(xlCellTypeConstants, xlNumbers).Value
  End Sub

这应该适用

    Dim Arr() As Variant
    Sheets("Sheet1").Range("R32:W32").SpecialCells(xlCellTypeConstants, xlNumbers).Copy
    Sheets("Sheet1").Range("A1").PasteSpecial xlValues
    Arr = Range(Range("A1"), Range("A1").End(xlToRight))
    Dim R As Long
    Dim C As Long
    For R = 1 To UBound(Arr, 1) ' First array dimension is rows.
       For C = 1 To UBound(Arr, 2) ' Second array dimension is columns.
          MsgBox Arr(R, C)
    Next C
  Next R

1 个答案:

答案 0 :(得分:2)

试试这个

Sub Sample()
    Dim ws As Worksheet
    Dim Arr() As Variant
    Dim rng As Range, cl As Range
    Dim n As Long, i As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")

    Set rng = ws.Range("R32:W32")

    n = Application.WorksheetFunction.Count(rng)

    If n = 0 Then Exit Sub

    ReDim Arr(1 To n)

    i = 1

    For Each cl In rng
        If IsNumeric(cl.Value) Then
            Arr(i) = cl.Value
            i = i + 1
        End If
    Next cl

    '~~> Only for demonstration purpose
    For i = 1 To n
        Debug.Print Arr(i)
    Next i
End Sub