sql-server 从SQL Server获取数据到Excel VBA列表视图

bxgwgixi  于 2022-10-31  发布在  SQL Server
关注(0)|答案(1)|浏览(263)

我正在尝试获取数据库中的数据,并在列表视图中显示(userform)。我遇到了一个错误,说“类型不匹配”,我很困惑什么部分是不匹配的,我已经搜索了这个错误的含义,但是我已经用正确的数据类型声明了我所有的变量。但是因为我有空白或者空值,所以它显示了一个错误。在这一行If not IsNull(Records(j, i)) Then li.ListSubItems.Add , , Records(j, i)上,我试图在listview上显示null或empty,不匹配错误消失了,但如果column1为空,column2不为空,column2上的值将粘贴到column1上。

  1. Private Sub ListView_Data()
  2. On Error GoTo ERR_Handler
  3. Dim sql As String
  4. Dim con As ADODB.Connection
  5. Dim rst As New ADODB.Recordset
  6. Dim Records As Variant
  7. Dim i As Long, j As Long
  8. Dim RecCount As Long
  9. Set con = New ADODB.Connection
  10. con.Open "Provider=SQLOLEDB;Data Source=10.206.88.119\BIWFO;" & _
  11. "Initial Catalog=TESTDB;" & _
  12. "Uid=user; Pwd=pass;"
  13. sql = "select * from [TESTDB].[dbo].[tbl_MN_Omega_Raw]"
  14. rst.Open sql, con, adOpenKeyset, adLockOptimistic
  15. '~~> Get the records in an array
  16. Records = rst.GetRows
  17. '~~> Get the records count
  18. RecCount = rst.RecordCount
  19. '~~> Populate the headers
  20. For i = 0 To rst.Fields.count - 1
  21. ListView1.ColumnHeaders.Add , , rst.Fields(i).Name, 200
  22. Next i
  23. rst.Close
  24. con.Close
  25. With ListView1
  26. .View = lvwReport
  27. .CheckBoxes = False
  28. .FullRowSelect = True
  29. .Gridlines = True
  30. .LabelWrap = True
  31. .LabelEdit = lvwManual
  32. Dim li As ListItem
  33. '~~> Populate the records
  34. For i = 0 To RecCount - 1
  35. Set li = .ListItems.Add(, , Records(0, i))
  36. For j = 1 To UBound(Records)
  37. If not IsNull(Records(j, i)) Then li.ListSubItems.Add , , Records(j, i)
  38. 'End If
  39. Next j
  40. Next i
  41. End With
  42. ERR_Handler:
  43. Select Case Err.Number
  44. Case 0
  45. Case Else
  46. MsgBox Err.Description, vbExclamation + vbOKOnly, Err.Number
  47. End Select
  48. End Sub
oxosxuxt

oxosxuxt1#

你的类型不匹配与空值无关,它来自一个看起来很正常的语句:rst.RecordCount会传回Vartype LongLong,而将它指派给Long会掷回型别不符。
有3种方法可以解决此问题:
(1)将RecCount声明为变量
(2)将rst.RecordCount转换为长整数:RecCount = CLng(rst.RecordCount)
(3)根本不要使用RecCount,而是使用UBound(records, 2)(我更喜欢这种方法)。
要找到这样的错误,请禁用错误处理程序(注解On Error Goto ERR_Handler)。这将显示引发错误的行。
但是,当您有包含null的字段时,会有一个小问题:您不需要对这些值执行li.ListSubItems.Add,因此该行剩余字段的所有值都将向左“移位”。您还需要对空值运行ListSubItems.Add,例如

  1. Dim fValue As Variant
  2. fValue = Records(j, i)
  3. If IsNull(fValue) Then fValue = "" ' or maybe "(null)"
  4. li.ListSubItems.Add , , fValue

相关问题