ExcelTip.com
ExcelTip.com
Account Icon Account Icon Account Icon
Google Exceltip.com
JOIN OUR NEWSLETTER
  and receive for joining:
Free eBook Learn More!
Free Excel ADD-IN
Free Weekly Excel Tip
4 e-books in cd-rom
F1 Formulas & Functions
F1 Formulas & Functions
F1 EXCEL
F1 eBook (Spanish)
F1 EXCEL
Financial Statements.xls
 

» Fill a ListBox-control with values from another workbook using VBA in Microsoft Excel
VBA macro tip contributed by Erlandsen Data Consulting offering Microsoft Excel Application development, template customization, support and training solutions
From another open workbook
It's possible to set the RowSource-property for a ListBox- or ComboBox-control to get data from
another workbook by filling in something like this:
'[Filename.xls]Sheet1'!$B$1:$B$15
The other workbook must be open for the control to display any values.
With the macro below you can fill a ListBox-control with data from another closed workbook.
The macro opens the other workbook without the user noticing it,
fills the ListBox with data and closes the workbook without saving any changes.
This macro is supposed to be saved in the UserForm's modulesheet.
Private Sub UserForm_Initialize()
Dim ListItems As Variant, i As Integer
Dim SourceWB As Workbook
    With Me.ListBox1
        .Clear ' remove existing entries from the listbox
        ' turn screen updating off, 
        ' prevent the user from seeing the source workbook being opened
        Application.ScreenUpdating = False 
        ' open the source workbook as ReadOnly
        Set SourceWB = Workbooks.Open("C:\FolderName\SourceWorkbook.xls", _
            False, True)
        ListItems = SourceWB.Worksheets(1).Range("B2:B21").Value 
        ' get the values you want
        SourceWB.Close False ' close the source workbook without saving changes
        Set SourceWB = Nothing
        Application.ScreenUpdating = True
        ListItems = Application.WorksheetFunction.Transpose(ListItems) 
        ' convert values to a vertical array
        For i = 1 To UBound(ListItems)
            .AddItem ListItems(i) ' populate the listbox
        Next i
        .ListIndex = -1 ' no items selected, set to 0 to select the first item
    End With
End Sub
 
From a closed workbook that is opened and closed again without the user noticing it
With the macro below you can fill a ListBox control with input from another closed workbook.
The macro opens the closed workbook without the user noticing it, gets the values for the ListBox and closes
the source workbook without saving any changes. Copy the macro into the UserForm's module sheet.
Private Sub UserForm_Initialize()
Dim ListItems As Variant, i As Integer
Dim SourceWB As Workbook
    With Me.ListBox1
        .Clear ' remove existing entries from the listbox
        ' turn screen updating off, 
        ' prevent the user from seeing the source workbook being opened
        Application.ScreenUpdating = False 
        ' open the source workbook as ReadOnly
        Set SourceWB = Workbooks.Open("C:\FolderName\SourceWorkbook.xls", _
            False, True)
        ListItems = SourceWB.Worksheets(1).Range("B2:B21").Value
        ' get the values you want
        SourceWB.Close False ' close the source workbook without saving changes
        Set SourceWB = Nothing
        ListItems = Application.WorksheetFunction.Transpose(ListItems) 
        ' convert values to a vertical array
        For i = 1 To UBound(ListItems)
            .AddItem ListItems(i) ' populate the listbox
        Next i
        .ListIndex = -1 ' no items selected, set to 0 to select the first item
        Application.ScreenUpdating = True
    End With
End Sub
From a closed workbook by using ADO
With the macros below you can fill in an ListBox/ComboBox with input from another workbook without opening it.
Copy the macros into the UserForm's module sheet.
Private Sub UserForm_Initialize()
' fill ListBox1 with data from a closed workbook
' can also be used from other applications to read data from an open workbook
Dim tArray As Variant
    tArray = ReadDataFromWorkbook("C:\FolderName\SourceWbName.xls", "A1:B21")
    FillListBox Me.ListBox1, tArray
    Erase tArray
End Sub

Private Sub FillListBox(lb As MSForms.ListBox, RecordSetArray As Variant)
' fills lb with data from RecordSetArray
Dim r As Long, c As Long
    With lb
        .Clear
        For r = LBound(RecordSetArray, 2) To UBound(RecordSetArray, 2)
            .AddItem
            For c = LBound(RecordSetArray, 1) To UBound(RecordSetArray, 1)
                .List(r, c) = RecordSetArray(c, r)
            Next c
        Next r
        .ListIndex = -1 ' no item selected
    End With
End Sub

Private Function ReadDataFromWorkbook(SourceFile As String, _
    SourceRange As String) As Variant
' requires a reference to the Microsoft ActiveX Data Objects library 
' (menu Tools, References in the VBE)
' if SourceRange is a range reference:
'   this function can only return data from the first worksheet in SourceFile
' if SourceRange is a defined name reference:
'   this function can return data from any worksheet in SourceFile
' SourceRange must include the range headers
' examples:
' varRecordSetData = _
    ReadDataFromWorkbook("C:\FolderName\SourceWbName.xls", "A1:A21")
' varRecordSetData = _
    ReadDataFromWorkbook("C:\FolderName\SourceWbName.xls", "A1:B21")
' varRecordSetData = _
    ReadDataFromWorkbook("C:\FolderName\SourceWbName.xls", "DefinedRangeName")
Dim dbConnection As ADODB.Connection, rs As ADODB.Recordset
Dim dbConnectionString As String
    dbConnectionString = _
        "DRIVER={Microsoft Excel Driver (*.xls)};ReadOnly=1;DBQ=" & SourceFile
    Set dbConnection = New ADODB.Connection
    On Error GoTo InvalidInput
    dbConnection.Open dbConnectionString ' open the database connection
    Set rs = dbConnection.Execute("[" & SourceRange & "]")
    On Error GoTo 0
    ReadDataFromWorkbook = rs.GetRows 
    ' returns a two dim array with all records in rs
    dbConnection.Close ' close the database connection
    rs.Close
    Set rs = Nothing
    Set dbConnection = Nothing
    On Error GoTo 0
    Exit Function
InvalidInput:
    MsgBox "The source file or source range is invalid!", _
        vbExclamation, "Get data from closed workbook"
    Set rs = Nothing
    Set dbConnection = Nothing
End Function
From a closed workbook by using worksheet formulas/links
You can get input from another closed workbook by creating a (hidden) worksheet with formulas like this:
='C:\FolderName\[SourceWbName.xls]WorkSheetName'!A1
Copy this formula as far down and to the right as necessary to get the input values you want from the closed workbook.
Set the UserForm's RowSource property to the worksheet range (in the hidden worksheet)
containing the values from the closed (or open) workbook. The disadvantage with this method
is that the user will be prompted to update the links every time the workbook containing the formula links is opened.

Rate this tip
12 34 5
  RATING: 3.60
  VIEWS: 105959

READER COMMENTS (view all comments)


Error correction
Karim wrote on December 31, 1969 19:00 EST
Hi All,

Thanks for this great piece of code.

It worked for me after a slight modification. The rs.close should be place before the dbConnection.Close otherwise Excel will raise an error message.

Thanks again.
Karim



REGISTERED USERS - Click here to post comments


GUESTS (Click here to register)
Name
Comment Title
Comments

Preparing the Marketing Plan (Ama Marketing Toolbox Series New Edition)

Writing Excel Macros with VBA, 2nd Edition

The Basics of Finance: Financial Tools for Non Financial Managers

Managing by the Numbers: A Commonsense Guide to Understanding and Using Your Company's Financials: An Essential Resource for Growing Businesses

Business Plans Kit for Dummies (With CD-ROM)

The 11 Immutable Laws of Internet Branding

RELATED MICROSOFT EXCEL TIPS


Convert PDF Files to Excel






Excel VBA books
Accounting books
Business Plans
MS Office books
Taxes books

VIEW ALL BOOKS


  Advertise With Us                               

Tips

Add-In in VBA | Applications - Word, Outlook in VBA | Array Formulas | Cells, Ranges, Rows, and Columns in VBA | Counting | Custom Functions | Custom Functions in VBA | Database Formulas | Database in VBA | Date & Time Formulas | Date & Time in VBA | Events in VBA | Excel 2003 | Excel Chart | Excel Consolidating | Excel Counting | Excel Custom Functions using VBA | Excel Customizing | Excel Data | Excel Dates | Excel Editing | Excel Files | Excel Filter | Excel Format | Excel Formula | Excel General | Excel Grouping and Outlining | Excel Importing Text Files | Excel Information | Excel Keyboard Shortcuts | Excel Loan Formulas | Excel Macros - VBA | Excel Pivot Tables | Excel Printing | Excel Range Name | Excel Security - Protection | Excel Sorting | Excel Style | Excel Subtotals | Excel Summing | Excel Text | Excel Time | Excel Tools | Excel Worksheet, Workbook | Files, Workbook, and Worksheets in VBA | Financial Formulas | Formating in VBA | General Topics in VBA | Import and Export in VBA | Information Formulas | Keyboard & Other Shortcuts in VBA | Keyboard Formula Shortcuts | Links between Worksheet and Workbooks | Links in VBA | Logical Formulas | Lookup Formulas | Mail - Send and Receive in VBA | Menus, Toolbars, Status bar in VBA | Modules, Class Modules in VBA | Other Q&A Formulas | Printing in VBA | Protecting in VBA | Summing | Text Formulas | User Forms, Input boxes in VBA | Using Loops | Working with Formulas |

Tips by Version

Microsoft Excel 97 | Microsoft Excel 2000 | Microsoft Excel 2002 | All Microsoft Excel Versions | New in Excel 2002 | New in Excel 2003 - Office 11

Website

Home | Tip of Hour | Recommended Tips | Most Viewed Tips | Tips by Version | Submit a Tip | My Tips
Microsoft Excel Tutorials | Excel Links | Write for Us | About Us | Search Results | Tip Archives | Excel Forum | Excel Forum Archives

Excel Book

Excel 97 Book | Excel 2000 Book | Excel 2002 Book | Excel XP Book | Book Store

Terms and Conditions of use
The applications/code on this site are distributed as is and without warranties or liability. In no event shall the owner of the copyrights, or the authors of the applications/code be liable for any loss of profit, any problems or any damage resulting from the use or evaluation of the applications/code.

Copyright © 2003 ExcelTip.com
Microsoft, Microsoft Excel is a U.S. registered trademark of Microsoft Corporation
Site Developed By: Varien