VBA将字符串作为范围传递,类型不匹配错误

时间:2017-08-02 20:36:22

标签: vba excel-vba excel

我正在尝试将动态命名范围填充到msgBox中,但在行Set xRg = xTxt上收到类型不匹配错误。

以下是代码:

Sub showOfferRange()
Dim xRg As Range
Dim xTxt As String
Dim xCell As Range
Dim xStr As String
Dim xRow As Long
Dim xCol As Long

On Error Resume Next
 xTxt = ThisWorkbook.Names("named_range")
Set xRg = xTxt

If xRg Is Nothing Then Exit Sub
    On Error Resume Next
    For xRow = 1 To xRg.Rows.Count
        For xCol = 1 To xRg.Columns.Count
            xStr = xStr & xRg.Cells(xRow, xCol).Value & vbTab
        Next
    xStr = xStr & vbCrLf
    Next

MsgBox xStr

End Sub

非常感谢。

1 个答案:

答案 0 :(得分:3)

您无法将Range对象设置为String变量。因此类型不匹配。

这样做:

Set rng = Range("named_range") 'since it's a workbook level name anyway