简体   繁体   中英

Excel VBA: <Unable to get the Activate property of the Worksheet class>

I am downloading the xlsm template file to the user. Once the doc is opened after download, getting "Unable to get the Activate property of the Worksheet class" error in the line 'ThisWorkbook.Sheets("DataSheet").Activate' inconsistently. Unable to understand what am i doing wrong.

My Code is,

Sub GetData(hostName As String, id As String)

  'Construct the Complete URL to get the saved view data
  Dim URL As String
  URL = hostName + "/Controller/Action?param=" + id

  ThisWorkbook.Sheets("DataSheet").Activate
  ThisWorkbook.Sheets("DataSheet").Cells.ClearContents

  With ActiveSheet.QueryTables.Add( _
        Connection:="URL;" + URL, _
        Destination:=Range("a1")) _
        .BackgroundQuery = True
        .TablesOnlyFromHTML = True
        .Refresh BackgroundQuery:=False
        .SaveData = True
  End With
End Sub

Any Ideas?

Update: Getting this error only for the first time opened after downloading (I am downloading to the user from my app - macro enabled doc - XLSM ). Once i closed the doc and open again, it is working fine :(

try changing your code as below:

Sub GetData(hostName As String, id As String)

  'Construct the Complete URL to get the saved view data
  Dim URL As String
  URL = hostName + "/Controller/Action?param=" + id

  ThisWorkbook.Sheets("DataSheet").Cells.ClearContents ' leaves formatting

  With Sheets("DataSheet").QueryTables.Add( _
        Connection:="URL;" + URL, _
        Destination:=Range("a1")) _
        .BackgroundQuery = True
        .TablesOnlyFromHTML = True
        .Refresh BackgroundQuery:=False
        .SaveData = True
  End With
End Sub

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