0

我正在将 xlsm 模板文件下载给用户。下载后打开文档后,在 'ThisWorkbook.Sheets("DataSheet").Activate' 行中出现“无法获取 Worksheet 类的激活属性”错误不一致。无法理解我做错了什么。

我的代码是,

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

有任何想法吗?

更新:仅在下载后第一次打开时出现此错误(我正在从我的应用程序-启用宏的文档-XLSM 下载给用户)。一旦我关闭文档并再次打开,它工作正常:(

4

1 回答 1

1

尝试更改您的代码如下:

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
于 2013-05-23T10:44:18.840 回答