ListObject返回一个字符串

时间:2017-10-06 18:15:14

标签: excel-vba vba excel

我想从一个函数返回一个ListObject,但似乎它隐式地将它转换为一个字符串。我很迷惑。有人可以指出我做错了吗?

Sub TestMyFunction()
    Dim MyTable As ListObject
    Set MyTable = RangeToTable
    Debug.Print MyTable '---MyTable = "Table1"
    MyTable.Unlist
End Sub

Private Function RangeToTable() As ListObject
    Dim wks As Worksheet
    Set wks = ActiveWorkbook.Worksheets(sREPORT_DATA_1)

    Dim rngTable As Range
    Set rngTable = wks.Range("A1").CurrentRegion

    Set RangeToTable = wks.ListObjects.Add(xlSrcRange, rngTable, , xlYes)
End Function

1 个答案:

答案 0 :(得分:-1)

wks.ListObjects.Add(xlSrcRange,rngTable,xlYes)中的ListObjects是一个集合。集合项有两个属性,名称和值。在这种情况下,名称是"表1"因为你在创建它之后没有为rngTable指定一个名字。执行.Add时,添加的集合项的名称为" Table1"并且值是内存中rngTable结构的地址。

执行Debug.Print MyTable时,它是一个集合项,它打印集合项的默认属性,即名称,"表1"。

Sub TestMyFunction()
    Dim MyLO As ListObject
    Set MyLO = RangeToTable
    Debug.Print MyLO '---MyLO = "Table1"
    MyLO.Unlist
End Sub

Private Function RangeToTable() As ListObject
    Dim wks As Worksheet
    Set wks = ActiveWorkbook.Worksheets(sREPORT_DATA_1)

    Dim rngTable As Range
    Set rngTable = wks.Range("A1").CurrentRegion

    Set RangeToTable = wks.ListObjects.Add(xlSrcRange, rngTable, , xlYes)
End Function

以下链接可能会为您清除。 How do I reference tables in Excel vba?