简体   繁体   中英

Excel VBA get table range on unactive worksheet

I cannot figure out why this statement does not work.

Rng = Worksheets(sheetName).ListObjects(table).Range.Select

I have a sheet "sheetX" with a button that invokes a subprocess "export_json" in the global workspace "Thisworkbook". I want the subprocess in "Thisworkbook" to reference a table range on "sheetX" at "A2" but it gives an error "Application-defined or Object-defined error". I do not want to use Application.Goto

Why is that? I'm overlooking something basic

Public Sub CommandButton1_Click()
    sheet = ActiveSheet.Name
    Call ThisWorkbook.export_json(sheet)
End Sub

Public Sub export_json(sheetName)
    table = ThisWorkbook.get_table(Worksheets(sheetName).Range("A2"))
    Rng = Worksheets(sheetName).ListObjects(table).Range.Select
    Rng = Selection.Address

table is of type string and sheet is the correct sheet name of type string so that is not the problem.

Your syntaxing looks a little off, when your trying declare Rng in the function export_json() you should pass it as a string.

Public Sub CommandButton1_Click()

    Dim sheetX As String
    sheetX = ActiveSheet.Name
    Call export_json("sheetX")

End Sub

Private Function export_json(sheetName As String)

    table = ThisWorkbook.get_table(Worksheets(sheetName).Range("A2"))
    Worksheets(sheetName).ListObjects(table).Range.Select

End Function

Try the code below, there's no need to use Select .

Also, it is not clear to me why you keep the code of your Function in ThisWorkbook module, instead of a regular module.

Public Sub CommandButton1_Click()

    Dim TableRangeString As String

    TableRangeString = ThisWorkbook.export_json(ActiveSheet.Name)

    ' for debug
    MsgBox TableRangeString

End Sub

Public Function export_json(sheetName) As String
    ' use the function to return the Range.Address by changing it to return a String

    Dim Rng As Range

    Set Rng = Worksheets(sheetName).Range("A2").ListObject.Range
    export_json = Rng.Address

End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM