从Excel执行SQL查询

我有点卡住了一段时间在一个小的项目,以产生在几个Excel表中的几个SQL查询的结果,我想使用SQL Server 2008,这是我第一次代码VBA我试过这个代码(对于一个SQL单查询),但我仍然有编译问题

Sub New_Feuil1() ThisWorkbook.Activate 'First clear the contents from the query Worksheets("Feuil1").Select Range("A2").Select Do Until ActiveCell = "" ActiveCell.Offset(1).Select Loop Range("A4", ActiveCell.Offset(-1, 3)).ClearContents 'Get reporting date ReportingDate = ThisWorkbook.Sheets("Parameters").Range("D1") 'Format the value for use in the SQL query ReportingDateFor = Format(ReportingDate, "yyyy-mm-dd") Worksheets("Feuil1").Select Range("A1").Select Dim cnn As New ADODB.Connection Dim rst As New ADODB.Recordset Dim StrQuery1 As String Dim ConnectionString As String ConnectionString ="ODBC;" & _ "Driver={SQL Server Native Client 10.0};" & _ "Server=187.125.254.231;" & _ "Database=database;" & _ "UID=sa; PWD=pwd" cnn.Open ConnectionString cnn.CommandTimeout = 900 'Queries to be executed StrQuery1 = StrQuery1 & "Select Id from Users" rst.Open StrQuery1, cnn, adOpenForwardOnly, adLockReadOnly rst.Close Debug.Print "StrQuery1:"; StrQuery1 cnn.Close ThisWorkbook.Sheets("Central Dashboard").Select Sheets("Feuil1").Range("A2").CopyFromRecordset rst End Sub 

有没有其他解决scheme?

看来你是编程新手:)在使用任何variables之前,请先声明它们,这将有助于你快速理解它们。

喜欢:

 Dim ReportingDate as Date ReportingDate = ThisWorkbook.Sheets("Parameters").Range("D1") Dim ReportingDateFor As String ReportingDateFor = Format$(ReportingDate, "yyyy-mm-dd") 

还要检查你的连接string。 试试这个连接string。

 ConnectionString = "Driver={SQL Server Native Client 10.0};Server=187.125.254.231;Database=database;UID=sa; PWD=pwd" 

除此之外,看你的代码连接到服务器,打开logging集,closureslogging集,最后closures连接,然后尝试检索结果。 逻辑上这将永远不会工作:) 🙂

尝试这个:

 Dim cnn As New ADODB.Connection Dim rst As New ADODB.Recordset Dim cmd As ADODB.Command Dim ConnectionString As String ConnectionString = "Driver={SQL Server Native Client 10.0};Server=187.125.254.231;Database=database;UID=sa; PWD=pwd" cnn.Open ConnectionString 'Queries to be executed Dim StrQuery1 As String StrQuery1 = StrQuery1 & "Select Id from Users" 'Prepare SQL execution cmd.Name = "SelectUsers" cmd.ActiveConnection = conn cmd.CommandText = StrQuery1 Set rst = cmd.Execute If Not rst.EOF Then With Sheets(1).Cells ' Enter your sheet name and range here .ClearContents ' clears the entire sheet .CopyFromRecordset rst ' copy the result End With Else MsgBox "no records found.." End If 'After work done close connection On Error Resume Next rst.Close cnn.Close Set rst = Nothing Set cnn = Nothing