【发布时间】:2018-08-24 09:13:58
【问题描述】:
将 Excel 2016 64 位与 Access DB 结合使用。我创建了一个从数据库中获取历史数据的函数。它在调试窗口中运行并填充记录集。但是,一旦我尝试将数据写入 Excel 工作表,VBA 就会直接退出而不会出现错误。
我尝试了几种将数据填充到 excel 中的不同方法,包括 .copyfromrecordset、将数据转换为字符串、传递给临时变量。没运气。如果我运行与 Sub 相同的代码(根据需要进行调整),它会完美运行。如果我尝试先将值传递给 sub,然后再传递给工作表,它也会失败。只要涉及功能,它就会失败。我已经搜索了答案,但找不到任何东西。有任何想法吗?
Function DAM_DD(Type_input As String, Tenor_input As String, Field_output As String, Optional Date_input As String, Optional Date_input2 As String, Optional target_cell As Range) As Variant
Dim rst As ADODB.Recordset
Dim cnt As ADODB.Connection
Dim stQuery As String, tbl_input As String, tenor_coupon As String
'<<< Bunch of code to fill in sql variables >>>
stQuery = "Select " & Field_output & " From " & tbl_input & " Where (" &
Date_input & " and Type=""" & Type_input & """ and " & tenor_coupon & ");"
'Execute query and return to a recordset
Call DAM_DB_Connection(stQuery, rst, cnt)
'Return results to excel
If rst.RecordCount <= 1 Then
DAM_DD = rst.Fields(0).Value
Else: Call Get_DAM_Hist(rst, target_cell)
End If
'Close database connection and clean up
Call Close_DB(rst, cnt)
End Function
Sub DAM_DB_Connection(stQuery As String, rst As ADODB.Recordset, cnt As ADODB.Connection)
Dim cmd As ADODB.Command
Dim stcon As String 'SQL Connection string
Set cnt = New ADODB.Connection
Set rst = New ADODB.Recordset
Set cmd = New ADODB.Command
'Define database connection string
stcon = "Provider=Microsoft.ACE.OLEDB.16.0;"
stcon = stcon + "Data Source='C:\Users\DAM_DB.accdb';"
'Open database connection
cnt.ConnectionString = stcon
cnt.Open
cmd.CommandType = adCmdText
cmd.ActiveConnection = cnt 'Set the command connection string
cmd.CommandText = stQuery
'Execute query and return to a recordset
rst.CursorLocation = adUseClient 'Needed for recordset count
rst.CursorType = adOpenKeyset
rst.Open stQuery, cnt, adOpenDynamic, adLockOptimistic, adCmdText
rst.MoveFirst
'Close connection in separate Sub Close_DB
End Sub
Sub Get_DAM_Hist(rst As ADODB.Recordset, target_cell As Range)
Dim ws As Worksheet
Dim Rw As Long, Col As Long, rst_end As Long, counter As Long
Dim rst_array As Variant, target_array As Variant
Set ws = Worksheets("Sheet1")
rst_end = rst.RecordCount
ReDim rst_array(0 To rst_end, 0 To rst_end)
rst_array = rst.GetRows(rst.RecordCount)
PrintArray rst_array, target_cell
' counter = 1
' Do While rst.EOF = False
' ws.Cells(counter, 8) = rst.Fields(0) <- Alternate version that fails Here
' ws.Cells(counter, 9) = rst.Fields(1)
' counter = counter + 1
' rst.MoveNext
' Loop
End Sub
Sub PrintArray(Data As Variant, target_cell As Range)
Dim Rw As Integer, Cl As Integer, i As Integer, j As Integer
Dim out_string As String
Rw = Range(target_cell).Row
Cl = Range(target_cell).Column
For i = LBound(Data, 1) To UBound(Data, 1)
For j = LBound(Data, 1) To UBound(Data, 1)
out_string = Trim(CStr(Data(i, j)))
Activesheet.Cells(Rw, Cl) = out_string '<--------- Fails here
Cl = Cl + 1
Next j
Rw = Rw + 1
Next i
End Sub
【问题讨论】:
-
感谢您的链接。评估命令对我有用。