[英]VBA ADODB.Recordset values disappear suddenly
從記錄集中的 mssql 數據庫加載數據時,所有字段都會正確填充。 如果我檢查 vba 調試器中的記錄集,所有字段都有值。 一旦我訪問一個字段 fe 將值分配給一個變量,一些字段值似乎就消失了。 然后,當我簽入調試器時,相同的字段將“空”作為值。 知道問題可能是什么嗎?
Sub FillData(query)
On Error GoTo eh
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
rs.Source = query
Dim cn As Object
Set cn = GetConnection()
Dim cnstr As String
cnstr = GetConnectionString()
cn.Open cnstr
With rs
.ActiveConnection = cn
.Open
If rs.EOF And rs.BOF Then
Else
Do While Not rs.EOF
'if i check here in debugger all fields have values
article = rs.Fields("ARTICLE")
lst_nr = rs.Fields("LST_NR")
desc = rs.Fields("DESC")
CurrencyCustomer = rs.Fields("CUR_CUST")
CurrencyPartner = rs.Fields("CUR_PART")
'if i check here again, some lost the values. Also not all variables are populated...
'processing values
rs.MoveNext
Loop
End If
.Close
End With
cleanUp:
If Not (rs Is Nothing) Then
If (rs.State And eState.adStateOpen) = eState.adStateOpen Then
rs.Close
Set rs = Nothing
End If
End If
If Not (cn Is Nothing) Then
If (cn.State And eState.adStateOpen) = eState.adStateOpen Then
cn.Close
Set cn = Nothing
End If
End If
GeneratePdf
Exit Sub
eh:
MsgBox Err.Description
GoTo cleanUp
End Sub
你正在做的一些事情看起來很冗長和多余。
我們可以使用.OpenRecordset
命令縮短序言。 也不需要清理。 沒有引用的對象會被垃圾回收。 如果我們使用With
塊來確保我們的記錄集 object 在 Sub 完成時沒有 object 引用。
Option Explicit
Public Sub FillData(ByVal query As String)
On Error GoTo eh
With CurrentDB.OpenRecordset(query, dbOpenDynaset)
If Not (.BOF And .EOF) Then
Do While Not .EOF
'if i check here in debugger all fields have values
article = .Fields("ARTICLE")
lst_nr = .Fields("LST_NR")
desc = .Fields("DESC")
CurrencyCustomer = .Fields("CUR_CUST")
CurrencyPartner = .Fields("CUR_PART")
'if i check here again, some lost the values. Also not all variables are populated...
'processing values
.MoveNext
Loop
End If
.Close
End With
eh:
If err.Number <> 0 Then
MsgBox Err.Description
End If
GeneratePdf
End Sub
看起來,ADODB.Recordset 不喜歡在填充字段時以不同的順序訪問它(SQL-SERVER)。 至少我最近的測試指出了這個方向。 作為一種解決方法,我遍歷記錄集並在字典中填充字段並將字典存儲在集合中。 這樣,a 仍然可以通過其 name 屬性訪問字段。 作為獎勵,只要我需要記錄集並且可以在填充集合后立即關閉它,我就不必保持連接打開。
...
Dim articles As New Collection
Dim article As Object
Do While Not rs.EOF
Set article = CreateObject("Scripting.Dictionary")
For Each fld In rs.Fields
article.Add fld.Name, fld.Value
Next
articles.Add article
rs.MoveNext
Loop
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.