我試圖在我的資料庫中獲取資料并將其顯示在我的串列視圖(用戶表單)中。我遇到了一個錯誤,說“型別不匹配”我很困惑不匹配的部分,已經搜索了這個錯誤的含義,但我已經用正確的資料型別宣告了我的所有變數。但由于我有空格或空值,它會顯示錯誤。在這一行上If not IsNull(Records(j, i)) Then li.ListSubItems.Add , , Records(j, i),我試圖在 listview 上顯示 null 或空,不匹配錯誤消失了,但如果 column1 為空白且 column2 不為空,則 column2 上的值將粘貼到 column1 上。
Private Sub ListView_Data()
On Error GoTo ERR_Handler
Dim sql As String
Dim con As ADODB.Connection
Dim rst As New ADODB.Recordset
Dim Records As Variant
Dim i As Long, j As Long
Dim RecCount As Long
Set con = New ADODB.Connection
con.Open "Provider=SQLOLEDB;Data Source=10.206.88.119\BIWFO;" & _
"Initial Catalog=TESTDB;" & _
"Uid=user; Pwd=pass;"
sql = "select * from [TESTDB].[dbo].[tbl_MN_Omega_Raw]"
rst.Open sql, con, adOpenKeyset, adLockOptimistic
'~~> Get the records in an array
Records = rst.GetRows
'~~> Get the records count
RecCount = rst.RecordCount
'~~> Populate the headers
For i = 0 To rst.Fields.count - 1
ListView1.ColumnHeaders.Add , , rst.Fields(i).Name, 200
Next i
rst.Close
con.Close
With ListView1
.View = lvwReport
.CheckBoxes = False
.FullRowSelect = True
.Gridlines = True
.LabelWrap = True
.LabelEdit = lvwManual
Dim li As ListItem
'~~> Populate the records
For i = 0 To RecCount - 1
Set li = .ListItems.Add(, , Records(0, i))
For j = 1 To UBound(Records)
If not IsNull(Records(j, i)) Then li.ListSubItems.Add , , Records(j, i)
'End If
Next j
Next i
End With
ERR_Handler:
Select Case Err.Number
Case 0
Case Else
MsgBox Err.Description, vbExclamation vbOKOnly, Err.Number
End Select
End Sub
uj5u.com熱心網友回復:
您的型別不匹配與空值無關。它來自一個看起來相當不可疑的陳述句:rst.RecordCount回傳 Vartype LongLong,并將其分配給 aLong會引發型別不匹配。
您有 3 種方法可以解決此問題:
(1) 宣告RecCount為 Variant
(2) 轉換rst.RecordCount成 Long: RecCount = CLng(rst.RecordCount)
(3) 根本不使用RecCount,而是使用UBound(records, 2)(我更喜歡這種方法)。
要查找此類錯誤,請禁用您的錯誤處理程式(注釋On Error Goto ERR_Handler)。這將顯示引發錯誤的行。
但是,當您的欄位包含 時存在一個小問題null:您不會li.ListSubItems.Add為這些值執行 a,因此該行其余欄位的所有值都將“移動”到左側。您還需要ListSubItems.Add為空值運行,例如使用
Dim fValue As Variant
fValue = Records(j, i)
If IsNull(fValue) Then fValue = "" ' or maybe "(null)"
li.ListSubItems.Add , , fValue
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/519613.html
標籤:sql服务器vba
