自动化错误80040e07使用cn.Execute(strSql)

时间:2017-04-19 20:21:06

标签: sql excel-vba vba excel

我有一个宏,它组装一个SQL查询以发送给Access。 它有5个变量(excel值)正常工作

当我添加第六个时,会生成标题中的错误。

错误之前执行中的屏幕截图。 鼠标保持在变量上以显示值。80040e07

Public Sub sum()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection =Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\Gr-001\data\GR-DEPTS\999-SHRD\data\GRHours.accdb;"
'validation
If Range("B3").Value <> "" And (Range("B4").Value <> "" Or Range("C4").Value <> "") Then
MsgBox "You cannot have both single date and date range entered at the same time.", vbOKOnly + vbCritical, "Error"
Exit Sub
End If
Dim w As String

'beginning of SQL string
strSql = "select sum(hours) from GRHours "

w = ""

'check criteria for employee
If Range("B2").Value <> "" Then w = w & " employee = '" & Range("B2").Value & "' "

'check criteria for date (single)
If Range("B3").Value <> "" Then
If w <> "" Then w = w & " AND "
w = w & " [date] = CDATE('" & Range("B3").Value & "') "
End If

'check criteria for date (beginning)
If Range("B4").Value <> "" Then
If w <> "" Then w = w & " AND "
w = w & " [date] >= CDATE('" & Range("B4").Value & "') "
End If

'check criteria for date (end)
If Range("C4").Value <> "" Then
If w <> "" Then w = w & " AND "
w = w & " [date] <= CDATE('" & Range("C4").Value & "') "
End If

'check criteria for job
If Range("B6").Value <> "" Then
If w <> "" Then w = w & " AND "
w = w & " job = '" & Range("B6").Value & "' "
End If

'check criteria for task
If Range("B7").Value <> "" Then
If w <> "" Then w = w & " AND "
w = w & " task = '" & Range("B7").Value & "' "
End If

'NEW INSERTION HERE - check criteria for week
If Range("B5").Value <> "" Then
If w <> "" Then w = w & " AND "
w = w & " week = '" & Range("B5").Value & "' "
End If
'END NEW INSERTION


'end of SQL string
If w <> "" Then strSql = strSql & " WHERE " & w

'send string to access
cn.Open strConnection
Set rs = cn.Execute(strSql)
ActiveSheet.Range("B9").CopyFromRecordset rs
'End If
End Sub

0 个答案:

没有答案