【问题标题】:Excel VBA: form control listbox with multi-columns -- how to populate from ADO recordset?Excel VBA:具有多列的表单控件列表框——如何从 ADO 记录集中填充?
【发布时间】:2017-05-26 15:28:24
【问题描述】:

由于兼容性问题,我不得不在我的电子表格上使用 Excel 表单控件列表框(相对于 ActiveX)控件。我正在尝试使用 ADO 记录集中的三个字段填充它,但我遇到了问题,因为自从我使用表单控件以来已经有一段时间了。

这是我为我的 ActiveX 列表框编写的代码。您能否指出一个从 ADO 记录集填充具有多列的表单控件列表框的示例?

提前感谢您在进行此转换时提供的任何帮助!

-- 汤姆

Private Sub Worksheet_Activate()
 On Error GoTo Err_Worksheet_Activate
 Dim cnn As ADODB.Connection
 Dim rst As ADODB.Recordset
 Dim i As Integer

     Set cnn = New ADODB.Connection

     cnn.ConnectionString = gcstr_Connection ' a global property with the connection string defined elsewhere. The connection is to a SQL Server database.

      cnn.Open

      Set rst = cnn.Execute("SELECT [FieldA], [FieldB], [FieldC] FROM dbo.", , adCmdText)

      rst.MoveFirst

      With Me.lst_System
          .Clear
          Do
          .AddItem
          .List(i, 0) = rst![FieldA]
          .List(i, 1) = rst![FieldB]
          .List(i, 2) = rst![FieldC]
          i = i + 1
              rst.MoveNext
          Loop Until rst.EOF
      End With

 Exit_Worksheet_Activate:
      On Error Resume Next
      rst.Close
      cnn.Close
      Set rst = Nothing
      Set cnn = Nothing
      Exit Sub

 Err_Worksheet_Activate:
      MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
      Err.Clear
      Resume Exit_Worksheet_Activate
 End Sub

【问题讨论】:

  • 我忘了添加,这个列表框在电子表格中,而不是在用户表单中。

标签: excel vba controls


【解决方案1】:

不知道表单控件是否可以支持像 ActiveX 列表框这样的多列,因此您可能需要考虑以不同的方式添加它们..

以下是如何删除所有/添加项目的示例,希望对您有所帮助:

'to remove all previous items
Me.Shapes("lst_System").ControlFormat.RemoveAllItems
'to add item
Me.Shapes("lst_System").ControlFormat.AddItem "SomeStringValue"

【讨论】:

    猜你喜欢
    • 2014-10-21
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多