|
请教各位一下,我想通过Public Sub TExecuteSQL(ByVal strSQL As String, Optional ByVal PathStr As String)函数来实现给定sql语句strSQL和文件全名PathStr自动进行sql查询并将结果输出为动态数组,本来已经实现运行了好几天都没问题,但是现在突然将代码复制到新的excel文件里面就报错了,错误信息:参数类型不正确,或不在可以接受的范围之内,或与其他参数冲突请帮忙看看到底是什么问题,谢谢
代码如下:(黄色部分为出现错误的位置)
Public Sub TExecuteSQL(ByVal strSQL As String, Optional ByVal PathStr As String) 'TEST
Dim Conn As Object, Rst As Object
Dim strConn As String
Dim i As Integer, j As Integer
On Error GoTo ExecuteSQL_Error
Set Conn = CreateObject("ADODB.Connection")
Set Rst = CreateObject("ADODB.Recordset")
If PathStr = "" Then PathStr = ThisWorkbook.FullName
Select Case Application.Version * 1
Case Is <= 11
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" & PathStr
Case Is >= 12
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathStr & ";Extended Properties=""Excel 12.0;HDR=YES"";"""
End Select
Conn.CursorLocation = adUseClient
Conn.Open strConn
Set Rst = Conn.Execute(strSQL)
ReDim aRst(1 To Rst.RecordCount + 1, 1 To Rst.Fields.Count)
For i = 1 To UBound(aRst, 2)
aRst(1, i) = Rst.Fields(i - 1).Name
Next i
Rst.MoveFirst
For i = 2 To UBound(aRst, 1)
For j = 1 To UBound(aRst, 2)
aRst(i, j) = Rst.Fields(j - 1).Value
Next j
Rst.MoveNext
Next i
ExecuteSQL_Exit:
Set Rst = Nothing
Set Conn = Nothing
Exit Sub
ExecuteSQL_Error:
MsgBox "错误原因:" & Err.Description
Resume ExecuteSQL_Exit
End Sub
|
|