如何在立即数 window 中打印一个范围变量? Excel VBA

How can I print a range variable in the immediate window? Excel VBA

我正在尝试一些应该非常简单的事情。不过今天才开始学,不是很明白

到目前为止,这是我的代码:

Public Sub getCellData()
   Dim wb As Workbook: Set wb = ThisWorkbook
   Dim ws As Worksheet: Set ws = wb.Sheets(1)
   Dim rng As Range: Set rng = ws.Range(Cells(1, 2), Cells(4, 2))

   Debug.Print rng
End Sub

我正在处理的数据是这样的:

我不断收到 "Run-time error '13': Type mismatch" 我用谷歌搜索了这个错误,但我仍然不确定如何解决这个问题。我想立即打印变量 rng window.

Range 是一个对象,不是一个值。要输出值,您可以迭代 Range。另一种方法是在单个行或列上使用 Transpose 函数,然后 Join 获取 Range.[=21 中值数组的 String 值=]

示例代码:

Public Sub getCellData()
    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim ws As Worksheet: Set ws = wb.Sheets(1)

    ' you need to prefix Cells with ws. to clarify the reference
    Dim rng As Range: Set rng = ws.Range(ws.Cells(1, 2), ws.Cells(4, 2))

    ' you cannot debug print the object itself
    'Debug.Print rng

    ' iterate the range
    Dim rngCell As Range
    For Each rngCell In rng
        Debug.Print rngCell.Value
    Next rngCell

    ' use the Transpose function for a single row or column
    Dim strData As String
    Dim wsf As WorksheetFunction: Set wsf = Application.WorksheetFunction
    strData = Join(wsf.Transpose(rng.Value), ",")
    Debug.Print strData


End Sub

请注意,我将您的 Set rng = ... 更新为:

Set rng = ws.Range(ws.Cells(1, 2), ws.Cells(4, 2))

并添加 ws. 作为 Cells 的前缀,以便明确定义引用。

你可以为这样的东西编写一个简单的子程序:

Sub PrintRange(R As Range, Optional delim As String = ", ")
    Dim myRow As Range, V As Variant, i As Long
    For Each myRow In R.Rows
        ReDim V(1 To myRow.Cells.Count)
        For i = 1 To myRow.Cells.Count
            V(i) = myRow.Cells(1, i).Value
        Next i
        Debug.Print Join(V, delim)
    Next myRow
End Sub

然后 PrintRange rng 将按预期工作。