不同的Excel工作表的不同的SQL命令

使用哪些VBAmacros命令可以在工作表之间切换,以便执行特定的Workbook Connecton SQL命令?

我所尝试的是,要select一个工作表,在特定连接的SQL命令中写入特定于表的sql命令存储该命令,然后刷新工作簿以获取结果。 代码只在最初执行的工作表上执行,而不是我select的工作表。

Sheets("Alex").Select ' The SQL command text Dim comText As String comText = ... // the SQL command text ' Changes the workbook's SQL command text to the text in the code above With ActiveWorkbook.Connections("conCRM").ODBCConnection // conCRM - the name of the conection .commandText = comText End With ' Refreshes data from the database ActiveWorkbook.Connections("conCRM").Refresh 

在我看来,错误的是代码中的最后一行是针对整个工作簿而不是我需要的特定工作表。

看看这是否接近你想要做的。 它需要3个不同的SQL语句,为每个SQL语句添加一个表单,执行它并将每个结果放在一个新表单上。

 Sub addSQLResultsOnto3Sheets() Dim oConn As WorkbookConnection Dim oQt As QueryTable Dim oSh As Worksheet Dim i, SQL 'Get the existing connection's connection string Set oConn = ActiveWorkbook.Connections("conCRM") 'Three different SQL statements, to be output onto 3 different worksheets. SQL = Array("SELECT TOP 1 * FROM MyTable", "SELECT TOP 2 * FROM MyTable", "SELECT TOP 3 * FROM MyTable") For i = 0 To 2 'Add a new sheet "Results N" Set oSh = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)) oSh.Name = "Results " & (i + 1) 'Add a new sheet with SQL Set oQt = oSh.ListObjects.Add(xlSrcExternal, oConn.ODBCConnection.Connection, Destination:=oSh.Range("A1")).QueryTable oQt.CommandText = SQL(i) oQt.Refresh Next End Sub