1

我正在尝试编写一个宏来将托管在服务器上的 excel 文件导入工作簿。这是我到目前为止的代码。

Sub ranker()
'
' ranker macro
'

'
    Range("Ranker!A10:Ranker!Z100").ClearContents
    URL = Range("url!F2" & i).Text
    With ActiveSheet.QueryTables.Add(Connection:= _
        "FINDER;" & URL _
        , Destination:=Range("Ranker!$A$1:$Z$100"))
        .Name = "ranker"
        .CommandType = xlCmdTable
        .CommandText = Array("'MTD SAR$'")
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

我唯一的问题是它会弹出以下对话框。

对话框

我每次都需要选择“MTD SAR$”选项。我可以在 vba 代码中选择此选项以避免该对话框吗?任何帮助将不胜感激。

4

1 回答 1

0

我不记得querytable有能力指定你想要的工作表的方法。我已经使用 OLEDB 解决了这个问题。这是一个例子:

Sub Excel_QueryTable()

    Dim oCn As ADODB.Connection
    Dim oRS As ADODB.Recordset
    Dim ConnString As String
    Dim SQL As String

    Dim qt As QueryTable

    ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\SubFile.xls;Extended Properties=Excel 8.0;Persist Security Info=False"
    Set oCn = New ADODB.Connection
    oCn.ConnectionString = ConnString
    oCn.Open

    SQL = "Select * from ['MTD SAR$']"

    Set oRS = New ADODB.Recordset
    oRS.Source = SQL
    oRS.ActiveConnection = oCn
    oRS.Open

    Set qt = Worksheets(1).QueryTables.Add(Connection:=oRS, _
Destination:=Range("Ranker!$A$1"))

    qt.Refresh

    If oRS.State <> adStateClosed Then
        oRS.Close
    End If


    If Not oRS Is Nothing Then Set oRS = Nothing
    If Not oCn Is Nothing Then Set oCn = Nothing

End Sub

这是我使用的,当然是调整过的:Query table with Excel as Data Source

于 2013-02-17T04:33:29.787 回答