通过显示选择弹出窗口包装文本的列表框用户窗体解决方法

时间:2014-12-15 16:35:01

标签: excel vba listbox

用户询问了有关使用鼠标悬停工具在Listbox列中显示截断数据的问题。 “Dee”发布了以下解决方案(请参阅https://stackoverflow.com/a/15301355/4362915):

Option Explicit

Public ListItemInfo As Control

Private Sub UserForm_Initialize()
    Set ListItemInfo = Me.Controls.Add("Forms.TextBox.1", "ListItemInfo", False)
    With Me.ListItemInfo
        .Top = Me.ListBox1.Top
        .Left = Me.ListBox1.Left
        .Width = Me.ListBox1.Width
        .Height = Me.ListBox1.Height
        .MultiLine = True
    End With
End Sub

Private Sub ListBox1_Change()
    Me.ListItemInfo.text = GetSelectedItemsText
End Sub

Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    SwitchListItemInfo
End Sub

Private Sub UserForm_Click()
    SwitchListItemInfo
End Sub

Private Function GetSelectedItemsText() As String
    Dim text As String
    Dim i As Integer
    For i = 0 To Me.ListBox1.ListCount - 1
        If Me.ListBox1.Selected(i) Then
            text = text & Me.ListBox1.List(i) & vbNewLine
        End If
    Next i
    GetSelectedItemsText = text
End Function

Private Sub SwitchListItemInfo()
    If Me.ListItemInfo.text = "" Then Exit Sub
    Me.ListItemInfo.Visible = Not Me.ListItemInfo.Visible
    Me.ListBox1.Visible = Not Me.ListBox1.Visible
End Sub 

简而言之,Dee的代码从列表框的RowSource值中指定的选择范围填充ListBox1;当您双击其中一个项目时,会弹出一个新的TextBox,列出双击项目的内容。当然,所有这些都是完成的,因为当值太长时,ListBox无法包装文本并切断文本。

我有一个列表框,其中填充了从Access数据库中提取的5列数据。我经常遇到某些数据列被截断的问题 - 因此,Dee对弹出文本框的解决方案非常有吸引力。但是,我正在努力修改Dee的代码,以便从我的访问数据库中填充列表框,而不是ListBox属性的RowSource字段中的预先指定的范围。我正在努力做到这一点,但我猜这个解决方案对于专家来说非常明显,所以任何帮助都会非常非常感激。我当前列表框的代码如下:

Sub UserForm_Initialize()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim NoOfRecords As Long
  'Open the .accdb form database to retrieve data
  s = ActiveCell.Value
  Set db = OpenDatabase("\\BTT\test.accdb")
  'Define the first recordset
  Set rs = db.OpenRecordset("SELECT * FROM Entities WHERE [Entity Name] Like '" & s & "' & '*' ")
  'Determine the number of records in the recordset
  On Error GoTo ErrHandler
  With rs
    .MoveLast
    NoOfRecords = .RecordCount
    .MoveFirst
  End With
  'Set the number of ListBox columns = number of fields in the recordset
  ListBox1.ColumnCount = 5
  'Load the listbox with the retrieved records
  ListBox1.Column = rs.GetRows(NoOfRecords)
    'Cleanup
  rs.Close
  db.Close
  Call Easy
  Set rs = Nothing
  Set db = Nothing
lbl_Exit:
  Exit Sub
ErrHandler:
  MsgBox "No historical results for this entity"
  Exit Sub
End Sub

1 个答案:

答案 0 :(得分:0)

尝试

Set Me.Listbox1.Recordset = rs

未经测试但有更多信息here