所以我有一张Excel工作表,其中包含可由用户更改的开始日期和结束日期。我有一个第二张表,其中有一个单元格,用户可以在其中输入查询以获取该信息。我已经为查询分配了startDate和enDate,因此它可以引用这些单元格。我遇到的问题是,因为我从excel中提取查询,所以它不引用startdate和endate。有什么我可以做的来解决这个问题吗?这是查询:
select system_date where system_date >= ' " & startDate & "" and
system_date <= "" & endDate & "# and action_id = 15 and log_desc not
like '%svc_openlink_p%' order by system_date
以下是代码:
Sub Button1_Click()
Dim dbConnectStr As String
Dim dbConnectStr1 As String
Dim objmyconn As ADODB.Connection
Set objmyconn = New ADODB.Connection
Dim recordCount As Long
Dim sh1 As Worksheet, s2 As Worksheet
Dim j As Long, N As Long, r1 As Range
Dim dat As Variant
Dim Rng As Range
Dim startDate As String
Dim endDate As String
Dim dataName As String
Dim passWord As String
Dim serverName As String
Dim qryN As String
'code for the dates
startDate = Format(Worksheets("TotalExtraction").Range("C6").Value2, "dd-mmm-yyyy")
endDate = Format(Worksheets("TotalExtraction").Range("C8").Value2, "dd-mmm-yyyy")
'code for assigment
dataName = (Range("dataName").Value)
passWord = (Range("password").Value)
serverName = (Range("server").Value)
qryN = (Range("Query").Text)
dbConnectStr = "Provider=msdaora;User Id=" & Uname
dbConnectStr1 = "Provider=msdaora;User Id='" & dataName & "';Data Source='" & serverName & "';Pwd='" & passWord & "'"
objmyconn.ConnectionString = dbConnectStr & dbConnectStr1
objmyconn.Properties("Prompt") = adPromptAlways
objmyconn.Open dbConnectStr 'ConnectionString'
'Declare variables'
'Set objmyconn = New ADODB.Connection
Set Sql = New ADODB.Command
Set ds = New ADODB.Recordset
Dim strsql As String
Dim fld As ADODB.Field
Dim i As Long
i = 2
Worksheets("IndividualUsers").Activate
ActiveSheet.Range("B4:M30000").Clear
'Set and Execture SQL Command
Set Sql.ActiveConnection = objmyconn
Sql.CommandText = qryN
MsgBox qryN
Sql.CommandType = adCmdText
Sql.Execute
答案 0 :(得分:0)
考虑使用参数化查询,在执行之前将参数日期值绑定在VBA中。这避免了将值传递给select语句,这是不推荐的做法。此外,在这样做时,您不需要围绕参数连接引号。
将以下内容保存在查询范围(包括问号)
="SELECT system_date
FROM TableName
WHERE system_date BETWEEN ? AND ?
AND action_id = 15
AND log_desc NOT LIKE '%svc_openlink_p%'
ORDER BY system_date"
VBA脚本(结束部分)
...
'Set and Execture SQL Command
With Sql
.ActiveConnection = objmyconn
.CommandType = adCmdText
.CommandText = qryN
.Parameters.Append cmd.CreateParameter("startDateParam", adDate, adParamInput)
.Parameters(0).Value = startDate
.Parameters.Append cmd.CreateParameter("endDateParam", adDate, adParamInput)
.Parameters(1).Value = endDate
.Execute
End With
顺便说一句,请务必在查询中指定 TableName 并检查连接字符串。最后,确保日期格式与数据库正确对齐。通常在RDMS中,格式为YYYY-MM-DD
。