4

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

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

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

我正在使用的数据是这样的:

在此处输入图像描述

我不断收到“运行时错误'13':类型不匹配”我用谷歌搜索了这个错误,但我仍然不确定如何解决这个问题。我想在即时窗口中打印变量 rng。

4

2 回答 2

5

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

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会按预期工作。

于 2017-11-29T01:51:10.080 回答
5

Range是一个对象,而不是一个值。要输出值,您可以迭代Range. 另一种方法是Transpose在单个行或列上使用该函数,然后Join获取.StringRange

示例代码:

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,以便显式定义引用。

于 2017-11-29T01:43:48.220 回答