我已經創建了一張工作表,用於從Microsoft SQL數據庫中提取數據以生成日期爲StartDate
和EndDate
之間的客戶報告。使用單元格中的日期或Sql查詢中的命名範圍
我一直在玩一些東西,但一直沒有成功。我已經搜查過,但一直未能找到任何我曾經或能夠理解的東西。
我相信的問題是我在Excel中使用的日期的數據類型,並試圖將它傳遞給SQL查詢。我知道我需要以某種方式轉換它,以使其成爲可能並且正確。
如果我手動輸入日期到查詢它工作正常。但不適合客戶使用 我沒有這方面的經驗,我只是!扼殺我的方式通過它。如果有人會對我如此友善,這將是非常感激。
下面是我想使用
Sub DataExtract()
'
DataExtract Macro
'
' Create a connection object.
Dim cni96X As ADODB.Connection
Set cni96X = New ADODB.Connection
' Set Database Range
' Provide the connection string.
Dim strConn As String
Dim Lan As Integer
Dim OS As Integer
Dim PointID As String
' Set Variables
Lan = Range("Lan").Value
OS = Range("OS").Value
PointID = Range("PointID").Value
StartDate = Range("StartDate").Value
EndDate = Range("EndDate").Value
'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"
'Connect to 963 database on the local server.
strConn = strConn & "DATA SOURCE=(local);INITIAL CATALOG=i96X;"
'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"
'Now open the connection.
cni96X.Open strConn
' Create a recordset object.
Dim rsi96X As ADODB.Recordset
Dim rsi96X1 As ADODB.Recordset
Set rsi96X = New ADODB.Recordset
Set rsi96X1 = New ADODB.Recordset
With rsi96X
' Assign the Connection object.
.ActiveConnection = cni96X
' Extract the required records1.
.Open "SELECT ModuleLabel, originalAlarmTime FROM LastAlarmDetailsByTime WHERE (os = " & OS & " And theModule = N'" & PointID & "'AND AlarmCode = N'DI=1' And lan = " & Lan & " And originalAlarmTime BETWEEN N'" & StartDate & "' AND N'" & EndDate & "') ORDER BY originalAlarmTime DESC"
' Copy the records into sheet.
Range("PointLabel, TimeCallInitiated").CopyFromRecordset rsi96X
With rsi96X1
.ActiveConnection = cni96X
' Assign the Connection object.
.Open "SELECT originalAlarmTime FROM LastAlarmDetailsByTime WHERE (os = " & OS & " And theModule = N'" & PointID & "'AND AlarmCode = N'CDI1' And lan = " & Lan & " And originalAlarmTime BETWEEN N'" & StartDate & "' AND N'" & EndDate & "')ORDER BY originalAlarmTime DESC"
' Copy the records into sheet.
Sheet1.Range("TimeCallEnded").CopyFromRecordset rsi96X1
' Tidy up
.Close
我希望這是有道理的代碼。
您必須格式化您的日期,例如:'StartDate = Formta(Range(「StartDate」)。Value,[Format])'Where'[Format]'是'YYYYMMDD'或'YYYY-MM-DD' – 2016-05-02 16:09:26