Vba listbox in word

Содержание

  • 1 Add items to ListBox
  • 2 Add item to List Box
  • 3 Add names of all open workbooks to the list box
  • 4 Assign the data in a worksheet to RowSource of a ListBox
  • 5 Determining the selected item
  • 6 Evaluating Which Items Are Selected in the Multiselect List Box
  • 7 Get all selected items in a list box
  • 8 Get selected from ListBox
  • 9 Get the selected items in a ListBox
  • 10 Make sure the RowSource property is empty
  • 11 Select the items programmatically

Add items to ListBox

   <source lang="vb">

Sub ShowDialog()

   With UserForm1.ListBox1
       .MultiSelect = fmMultiSelectSingle
       .RowSource = ""
       .AddItem "January"
       .AddItem "February"
       .AddItem "March"
       .AddItem "April"
       .AddItem "May"
       .AddItem "June"
       .AddItem "July"
       .AddItem "August"
       .AddItem "September"
       .AddItem "October"
       .AddItem "November"
       .AddItem "December"
   End With
   UserForm1.Show

End Sub

</source>
   
  

Add item to List Box

   <source lang="vb">

Private Sub Form_Load()

   Dim obj As AccessObject
   For Each obj In CurrentData.AllTables
       Me.yourListBox.AddItem obj.Name
   Next obj

End Sub

</source>
   
  

Add names of all open workbooks to the list box

   <source lang="vb">

Sub UserForm_Initialize()

   Dim wkBook As Workbook
   For Each wkBook In Workbooks
       lstWorkbooks.AddItem wkBook.Name
   Next

End Sub

</source>
   
  

Assign the data in a worksheet to RowSource of a ListBox

   <source lang="vb">

Private Sub obMonths_Click()

   ListBox1.RowSource = "Sheet1!Months"

End Sub

</source>
   
  

Determining the selected item

   <source lang="vb">

 Private Sub OKButton_Click()
     Dim Msg As String
     Msg = "You selected item # "
     Msg = Msg & ListBox1.ListIndex
     Msg = Msg & vbNewLine
     Msg = Msg & ListBox1.Value
     MsgBox Msg
     Unload UserForm1
 End Sub
</source>
   
  

Evaluating Which Items Are Selected in the Multiselect List Box

   <source lang="vb">

Private Sub cmdRunReports_Click()

   Dim varItem As Variant
   Dim lst As ListBox
   Set lst = Me.yourList
   If lst.MultiSelect > 0 Then
       If lst.ItemsSelected.Count > 0 Then
           For Each varItem In lst.ItemsSelected
               DoCmd.OpenReport lst.ItemData(varItem), acViewPreview
           Next varItem
        End If
    End If

End Sub

</source>
   
  

Get all selected items in a list box

   <source lang="vb">

Private Sub OKButton_Click()

   If ListBox1.ListIndex = -1 Then
       msg = "Nothing"
   Else
       msg = ""
       For i = 0 To ListBox1.ListCount - 1
           If ListBox1.Selected(i) Then _
             msg = msg & ListBox1.List(i) & vbCrLf
       Next i
   End If
   MsgBox "You selected: " & vbCrLf & msg
   Unload Me

End Sub

</source>
   
  

Get selected from ListBox

   <source lang="vb">

Private Sub OKButton_Click()

   ActiveCell = ListBox1.Value
   Unload Me

End Sub

</source>
   
  

Get the selected items in a ListBox

   <source lang="vb">

 Private Sub OKButton_Click()
     Dim Msg As String
     Dim i As Integer
     Msg = "You selected" & vbNewLine
     For i = 0 To ListBox1.ListCount - 1
         If ListBox1.Selected(i) Then
             Msg = Msg & ListBox1.List(i) & vbNewLine
         End If
     Next i
     MsgBox Msg
     Unload UserForm1
 End Sub
</source>
   
  

Make sure the RowSource property is empty

   <source lang="vb">

Sub ShowDialog1()

   With UserForm1
       .ListBox1.RowSource = "Sheet1!Months"
       .obMonths.Value = True
   End With
   UserForm1.Show

End Sub

</source>
   
  

Select the items programmatically

   <source lang="vb">

Private Sub SelectAllButton_Click()

   For r = 0 To ListBox1.ListCount - 1
       ListBox1.Selected(r) = True
   Next r

End Sub

</source>

I need to get all the list-items of a listbox not only selected.
For example I have a list box with following list item:

A
C
K
L

How I can show them all in Immediate window?

Deduplicator's user avatar

Deduplicator

44.3k7 gold badges65 silver badges115 bronze badges

asked Jan 25, 2015 at 15:15

Abu Nayeem's user avatar

2

You can loop through all by using the column property of a ListBox. This Column(index, row) property return the value of the ListBox item at a specific index and row. For your simple ListBox the index will be 0. However, the row must be variable. For example you can use a for loop to get all the values of the ListBox.

for i = 0 to ListBox1.ListCount-1
    MsgBox(ListBox1.Column(0, i))
next i

answered Jan 25, 2015 at 15:36

timbmg's user avatar

timbmgtimbmg

3,1806 gold badges33 silver badges52 bronze badges

Sub get_all_list_item()

For i=0 to Listbox1.ListCount-1
Debug.Print Listbox1.List(0)
Next i

End Sub

answered Jan 29, 2015 at 17:56

Abu Nayeem's user avatar

Abu NayeemAbu Nayeem

971 gold badge1 silver badge8 bronze badges

Kevin Tang said:

Hello,

I have a ListBox in my VBA Form, named ListBox1
In UserForm_Initialize(), I have two statements to enable List Column Head:
ListBox1.ColumnCount = 2
ListBox1.ColumnHeads = True

My questions are:
1) how to set the Column Head’s name? such as «ID», «Name»….

You can’t. There is a bug in VBA and Microsoft never got round to fixing it.
Instead, set ColumnHeads to False, and position a couple of labels
immediately above the listbox whose captions will show the column headings.

2) how to add item into ListBox1 in both columns?? (e.g. Add (00001,

Kevin) )

Two possible approaches to this.

1. If you want to load the entire listbox in one go, put all your items into
a 2-dimensional array, and then assign the array to the List property of the
Listbox.

2. If you just want to add a single new row, use AddItem to add the new row
and assign text to the cell pointed to by the BoundCOlumn property (column 0
by default), Then add the text to the second column by using
ListBox1.List(n, 1) = «My new text», where n is the row number you want.

Студворк — интернет-сервис помощи студентам

Доброго времени суток!
Пересмотрел все похожие темы, но ответа на свой вопрос не нашел, помогите пожалуйста, если кто знает.

Заполняю ListBox на форме в Excel через RowSource, открывая для этого нужную рабочую книгу

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Private Sub UserForm_Initialize()
    fpath = "D:hrmph.xls"
    'Приложение Excel открыто
    Set MyExcel = GetObject(, "Excel.Application")
    'Открываю нужную книгу, зная путь
    MyExcel.Workbooks.Open fpath
    Set wbUserFile = MyExcel.ActiveWorkbook
    Set wsUserFile = wbUserFile.Worksheets(1)
    'Заполняю ListBox
    ListBox1.RowSource = "'[hrmph.xls]Лист1'!A2:C12"
    'можно заполнить по-другому, так тоже работает
    'tmpAddress = "'" & "[" & wbUserFile.Name & "]" & wsUserFile.Name & "'" & "!" & "A2:C12"
    'ListBox1.RowSource = tmpAddress
End Sub

ListBox заполняется данными, которые находятся по указанному адресу, проблем нет.
Теперь то же самое хочу проделать в форме приложения Word, используя тот же самый код, но ни один, ни другой вариант не работает, возникает ошибка «RunTime Error 438: object doesn’t support this property or method».
Подозреваю, что в ссылке на адрес диапазона ячеек не хватает объекта «приложение Excel», пробовал применить

Visual Basic
1
ListBox1.RowSource = MyExcel.tmpAddress

но тоже ничего не получилось. ListBox, расположенный на форме приложения Word данными из рабочей книги Excel не заполняются. Можно ли такое в принципе осуществить и если можно, то как?

  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • [Word] [VBA] populate listbox in userform with excel database

  1. Nov 4th, 2019, 07:02 AM


    #1

    illogic is offline

    Thread Starter


    New Member


    [Word] [VBA] populate listbox in userform with excel database

    Hello,

    i am having trouble with a userform i am trying to create.

    I want to populate a listbox in a userform in word with data that comes from an excel workbook.
    I have two listboxes.
    The first listbox get populated during userform initializiation.
    The second userform then gets populated with items from an excel workbook based on the selection that is made in the first listbox.

    I searched the internet for solutions and came across this thread:
    http://www.vbforums.com/showthread.p…ith-excel-data

    I am fairly new to VBA and i can’t quite figure out how to implement this code into my userform.
    The Data from the workbook recides on differents worksheets.

    As an easy example:

    Listbox1 containsitems get added during initialization)
    Animals
    Cities
    Software

    The Excel Workbook has three Worksheets:
    Animals
    Cities
    Software

    Each worksheet contains datasets in Column A only. But the amount of data varies.

    How would the code from that thread needed to be adjusted in order to make it work for me?

    I would appreciate it if someone would take the time to help me out with this problem.


  2. Nov 5th, 2019, 05:21 AM


    #2

    Re: [Word] [VBA] populate listbox in userform with excel database

    you can try like

    Code:

    Option Explicit
    Dim wb As Object
    
    Public Sub UserForm_Initialize()
        Dim sh As Object
    Set wb = GetObject("C:TempNew folderTestDatabase.xlsx")
    For Each sh In wb.sheets
        ListBox1.AddItem sh.Name
    Next
    End Sub
    
    
    Private Sub ListBox1_Click()
    Dim sh As Object, lrow As Long, rw As Long
    ListBox2.Clear
    Set sh = wb.sheets(ListBox1.Text)
    lrow = sh.Cells(sh.Rows.Count, 1).End(-4162).Row
    For rw = 1 To lrow
        ListBox2.AddItem sh.Cells(rw, 1)
    Next
    
    End Sub
    
    Private Sub UserForm_Terminate()
    wb.Application.Quit
    Set wb = Nothing
    End Sub

    as this is fairly simple, i changed this from using ADO, if the data became much more complex and you want to run queries on the data the ADO would be better, but for what you want so far this is fine

    change the pathfilename of your xlsx to suit, i opted to make the loading of listbox1 dynamic, if you add extra sheets or rename any the listbox is automatically correct when opening the userform, i have used late binding of excel workbook, so no reference is required and left the connection open until the userform is closed, rather than keep opening a connection

    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete


  3. Nov 6th, 2019, 04:13 AM


    #3

    illogic is offline

    Thread Starter


    New Member


    Re: [Word] [VBA] populate listbox in userform with excel database

    Hello,

    thanks for your reply.
    I implemented your code into my document and ran into the following error.

    Filename or class name not found during Automation operation (Error 432)
    The GetObject function requires either a valid file name with a path specification, or the name of a class that is registered with the system.

    The yellow marked Code while debugging is:

    Code:

        Set wb = GetObject("C:tempfindingsDB.xlsx")

    Hovering over it, it tells me:
    I double checked the path to the file for any typos and the path is correct.
    What else could be causing this issue?

    Here is the complete Code with all changes (not much has changed).

    Code:

    Option Explicit
    Public Sub UserForm_Initialize()
        Dim sh, wb As Object
        
        Set wb = GetObject("C:tempfindingsDB.xlsx")
        For Each sh In wb.Sheets
            ListBox5.AddItem sh.Name
        Next
    End Sub
    
    Private Sub ListBox5_Click()
    Dim sh As Object, wb As Object, lrow As Long, rw As Long
    ListBox6.Clear
    Set sh = wb.Sheets(ListBox5.Text)
    lrow = sh.Cells(sh.Rows.Count, 1).End(-4162).Row
    For rw = 1 To lrow
        ListBox6.AddItem sh.Cells(rw, 1)
    Next
    End Sub
    
    Private Sub UserForm_Terminate()
    Dim wb As Object
    wb.Application.Quit
    Set wb = Nothing
    End Sub


  4. Nov 6th, 2019, 04:31 AM


    #4

    illogic is offline

    Thread Starter


    New Member


    Re: [Word] [VBA] populate listbox in userform with excel database

    *deleted* double post, sorry…


  5. Nov 6th, 2019, 05:12 AM


    #5

    Re: [Word] [VBA] populate listbox in userform with excel database

    note where i dim wb, only in one place, though that should not cause your current error
    having wb dimensioned in each sub will cause errors and not work as intended
    also FYI items dimmed on one line still need to be typed individually, not just the last item
    Dim sh, wb As Object in this only wb is an object sh is just a default variant

    do you actually have a folder C:temp?
    i retested the code i posted, it worked correctly as intended, with your samples

    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete


  6. Nov 6th, 2019, 06:45 AM


    #6

    illogic is offline

    Thread Starter


    New Member


    Re: [Word] [VBA] populate listbox in userform with excel database

    Quote Originally Posted by westconn1
    View Post

    note where i dim wb, only in one place, though that should not cause your current error
    having wb dimensioned in each sub will cause errors and not work as intended
    also FYI items dimmed on one line still need to be typed individually, not just the last item
    Dim sh, wb As Object in this only wb is an object sh is just a default variant

    do you actually have a folder C:temp?
    i retested the code i posted, it worked correctly as intended, with your samples

    Ah ok thanks, i corrected that and wb is now dimensioned only outside of any sub.
    Thanks for the hint with dimmed items in one line, i did not know that.

    I got it working with the following code:

    Code:

    Option Explicit
    Dim wb As Object
    Dim xlApp As Object
    
    Public Sub UserForm_Initialize()
        Dim sh As Object
        Set xlApp = CreateObject("excel.Application")
        Set wb = xlApp.Workbooks.Open("C:tempfindingsDB.xlsx")
        wb.Application.Visible = False
        For Each sh In wb.Sheets
            ListBox5.AddItem sh.Name
        Next
    End Sub
    
    ...

    I don’t know why your method does not work for me.
    Would my workaround have any drawbacks in comparsion with your method?

    ***Edit

    I just found out that my solution does not work …
    Every time i click on a different item in listbox5, the code will try to open the workbook thus resulting in a prompt on the screen that it can only be opened as write-protected.

    Last edited by illogic; Nov 6th, 2019 at 07:37 AM.


  7. Nov 7th, 2019, 03:10 AM


    #7

    Re: [Word] [VBA] populate listbox in userform with excel database

    Every time i click on a different item in listbox5, the code will try to open the workbook thus resulting in a prompt on the screen that it can only be opened as write-protected.

    that should not happen as the code should only open the workbook once in the initialize event

    there is no other place that the workbook is opened in my code, and it is closed when the userform terminates, so reopening the userform should not be a problem, unless the userform is ended without closing

    Would my workaround have any drawbacks in comparsion with your method?

    the only drawback would be if the workbook is already open, the getobject method will (should) work whether the workbook is open or not

    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete


  8. Nov 8th, 2019, 03:23 AM


    #8

    illogic is offline

    Thread Starter


    New Member


    Re: [Word] [VBA] populate listbox in userform with excel database

    I made some additional changes and it seems to work now. I don’t get any Errors so far.
    But before i got it working i tried the following.

    Your original code was (of course with a modified path and filename):

    Code:

    Set wb = GetObject("C:tempfindingsDB.xlsx")

    Resulted in this Error:

    Filename or class name not found during Automation operation (Error 432)
    The GetObject function requires either a valid file name with a path specification, or the name of a class that is registered with the system. This error has the following cause and solution:
    The name specified for file name or class in a call to the GetObject function could not be found. Check the names and try again. Make sure the name used for the class parameter matches that registered with the system.

    Then i researched this error and found out that i should use ClassID, so i changed the line of code to this:

    Code:

    Set wb = GetObject("C:TempfindingsDB.xlsx", "Excel.Workbook")

    Which now resulted in a different error:

    ActiveX component can’t create object or return reference to this object (Error 429)
    Creating objects requires that the object’s class be registered in the system registry and that any associated dynamic-link libraries (DLL) be available.

    Source: https://docs.microsoft.com/de-de/off…ectedfrom=MSDN

    Then with further research i found this solution, which currently works.
    Don’t know if there is going to be any problems with that, at least not for now.

    Code:

    Option Explicit
    Dim wb As Object
    Dim xlApp As Object
    
    Public Sub UserForm_Initialize()
        Dim sh As Object
        On Error Resume Next
    'Get running Excel application
        Set xlApp = GetObject(, "Excel.Application")
        If Err.Number <> 0 Then
            Err.Clear
    'If no existing Excel app running, launch one
            Set xlApp = CreateObject("Excel.Application")
            If Err.Number <> 0 Then
                MsgBox "Cannot start Excel."
                Exit Sub
            End If
        End If
        xlApp.Visible = False
    'Open workbook
        Set wb = xlApp.Workbooks.Open("C:TempfindingsDB.xlsx")
        
        For Each sh In wb.Sheets
            ListBox5.AddItem sh.Name
        Next
    End Sub

    If i run into any errors in the near future, i will report back, otherwise i will mark this thread as «Solved».

    btw. Using ADO is alot more work to implement?
    I read somewhere that its faster and such, so should i stick with this current solution?
    The excel database is going to have 5 sheets and more with each sheet containing data which will increase over time.

    Anyways, thanks for helping me out so far. I appreciate it.


  9. Nov 8th, 2019, 03:59 AM


    #9

    Re: [Word] [VBA] populate listbox in userform with excel database

    so should i stick with this current solution?

    yes, unless you want to filter the data on multiple criteria, or the data is going to be thousands of rows
    it maybe possible to set the rowsource for the listbox which would probably be faster than looping though the rows and additems, though as an alternative you could assign the excel data to an array then loop through the array, this would be faster than the current code, but probably would not be noticeable in less than a couple of thousand rows, you could do some speed tests if it took your interest, i can give some code to do that

    the above code would still run into issues if the workbook is already open

    btw. Using ADO is alot more work to implement?

    not really much more, but in the existing scope probably overkill, also it depends what you want to do with the data beyond the existing request, excel automation and ADO can be run side by side, note also that while VBA is mostly backwards compatible, some code that can run in one version of excel may fail in the next

    the code i posted was tested, worked correctly without error, using office 2013 on win 10, i would be reasonably confident it would also work in office 2000 on XP, but i have no idea on later versions, i would have expected it to work, but that maybe the issue you are having

    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete


  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • [Word] [VBA] populate listbox in userform with excel database


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

Like this post? Please share to your friends:
  • Vba for excel to close
  • Vba library for excel
  • Vba learning in excel
  • Vba for excel sheet
  • Vba inserting rows in excel