首先是第一件事。这是我的代码。
Dim conn As ADODB.Connection
Dim rec1 As ADODB.Recordset
Dim connStr As String
Dim thisSql As String
Dim testStr As String
Sub Button3_Click()
Worksheets("Sheet5").Range("N1") = Worksheets("Sheet5").Range("N1") + 1
Set conn = New ADODB.Connection
connStr = "DSN=myDatabase;UID=myUsername;PWD=myPassword;APP=Microsoft Office 2013;WSID=myPCname;DATABASE=myDatabase"
conn.Open connStr
thisSql = "SELECT myDatabase.OrderNumber, myDatabase.CustomerName, myDatabase.ShipProd, myDatabase.Sum of Sales, myDatabase.InvoiceDate FROM myDatabaseAddress "
thisSql = thisSql & "WHERE (myDatabase.ShipProd Like '" & Worksheets("Sheet5").Range("C2") & "') "
thisSql = thisSql & "GROUP BY myDatabase.CustomerName, myDatabase.OrderNumber, myDatabase.InvoiceDate, myDatabase.ShipProd, myDatabase.OEELPrimarySlsCrdtWhse "
thisSql = thisSql & "HAVING (myDatabase.OEELPrimarySlsCrdtWhse Like 'MI%') "
thisSql = thisSql & "AND (myDatabase.InvoiceDate Between {ts '" & Worksheets("Sheet5").Range("E2") & "'} And {ts '" & Worksheets("Sheet5").Range("F2") & "'}) "
thisSql = thisSql & "ORDER BY myDatabase.CustomerName ASC"
Set rec1 = New ADODB.Recordset
rec1.Open thisSql, conn
Worksheets("Sheet5").Range("A3:F10000").Clear
With Worksheets("Sheet5").QueryTables.Add(Connection:=rec1, Destination:=Worksheets("Sheet5").Range("A3"))
.Name = "data"
.FieldNames = True
.Refresh BackgroundQuery:=False
End With
End Sub
我正在尝试使用参数发送查询并从SQL数据库中恢复一些结果。我想传递的参数之一是InvoiceDate必须介于其间的日期范围。这些日期位于单元格E2和F2中。当我运行代码时,我收到一个错误
Run-time error '-2147217913 (80040e07)':
[Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting date and/or time from character string.
当我在消息框中按“Debug”时,它突出显示代码
的行rec1.Open thisSql, conn
我尝试过多种方式格式化电子表格中的单元格,包括yyyymmdd和m / d / yyyy h:mm和mm / dd / yyyy hh:mm:ss。
我遇到的另一个问题是其中一个字段名称是“销售总额”。此部分生成错误,指出“of”是保留关键字。
如果有人提出任何建议,我们将不胜感激。
更新
我设法通过更改
来修复日期/时间错误thisSql = thisSql & "AND (myDatabase.InvoiceDate Between {ts '" & Worksheets("Sheet5").Range("E2") & "'} And {ts '" & Worksheets("Sheet5").Range("F2") & "'}) "
到
thisSql = thisSql & "AND (myDatabase.InvoiceDate Between '" & Worksheets("Sheet5").Range("E2") & "' And '" & Worksheets("Sheet5").Range("F2") & "') "
虽然,我仍在努力解决字段名称问题。我已经尝试将'myDatabase.Sum of Sales'放在单引号中,就像它在这里一样,但它只返回相应列中所有单元格中的“myDatabase.Sum of Sales”。