在本文中,我们将使用VBA在用户窗体中从封闭的工作簿中获取数据到列表框。

此示例的原始数据在“ 23SampleData.xls”工作簿上的区域A2:B10中,该文件位于文件路径“ D:\ Excelforum \ ExcelForum office \ excel提示旧代码\ Shared Macro \ 23 \”中。

ArrowSampleData

我们在主工作表上创建了两个命令按钮,用于运行两个不同的用户窗体。每个命令按钮都链接到不同的用户窗体。

ArrowMainSheet

逻辑解释

在此示例中,使用了两种不同的方式从封闭的工作簿中获取数据。这些是:- 。打开关闭的工作簿并获取数据。使用ADODB连接

打开关闭的工作簿并获取数据

通过将值分配给RowSource属性,可以设置ListBox控件的RowSource属性以从其他工作簿获取数据,如下所示:

‘[Filename.xls] Sheet1?!$ B $ 1:$ B $ 15 ListBox控件仅在打开另一个工作簿时才会显示值。

因此,要从关闭的工作簿中获取数据,我们将创建一个宏来打开另一个工作簿,而无需用户注意,并从工作簿中获取数据以在列表框中添加项目并关闭工作簿。

单击“选择”按钮将激活用户窗体“ UserForm1”。

用户窗体的Initialize事件用于在列表框中添加项目。此事件首先打开关闭的工作簿,然后将范围内的值分配给“ ListItems”变体。分配值后,工作簿将关闭,并将项目添加到列表框中。

ArrowClickingSelectButton

列表框用于从现有列表值中选择名称。按下“确定”按钮将显示所选名称。

ArrowSelectOutput

使用ADODB连接

ActiveX数据对象(ADO)是用于OLE DB连接的高级,易于使用的接口。它是用于访问和操作数据库中数据的编程接口。

为了创建ADODB连接,我们需要将ADO库添加到项目中。

要添加参考,请从“工具”菜单>“参考”中选择。

ArrowAddingReference

单击工作表上的“ ADODB连接”按钮将激活“ UFADODB”用户窗体。在此用户窗体的initialize事件中,我们使用ADODB连接从关闭的工作簿中获取数据。我们创建了一个自定义的用户定义函数(UDF)“ ReadDataFromWorkbook”以建立连接并从关闭的工作簿中获取数据到数组。

在初始化用户表单时,我们使用了另一个UDF“ FillListBox”在列表框中添加项目。列表框将在两列中显示数据,第一列包含名称,第二列包含年龄。

ArrowClickingADODBConnection

在列表框中选择项目后按“确定”按钮将显示有关所选项目的信息消息。

ArrowADODBOutput

请遵循以下代码

Option Explicit

Sub running()

UserForm1.Show

End Sub

Sub ADODBrunning()

UFADODB.Show

End Sub

'Add below code in UFADODB userform

Option Explicit

Private Sub CommandButton1_Click()

Dim name1 As String

Dim age1 As Integer

Dim i As Integer

'Assign the selected value in list box to variable name1 and age1

For i = 0 To ListBox1.ListCount - 1

If ListBox1.Selected(i) Then

name1 = ListBox1.Value

age1 = ListBox1.List(ListBox1.ListIndex, 1)

Exit For

End If

Next

'Unload the userform

Unload Me

'Displaying output

MsgBox "You have selected " & name1 & ". His age is " & age1 & " yrs."

End Sub

Private Sub UserForm_Initialize()

'Filling ListBox1 with data from a closed workbook

Dim tArray As Variant

'Calling function ReadDataFromWorkbook for getting data from specified range to array

'Change path according to your requirement, "Sample_data" is named defined range

tArray = ReadDataFromWorkbook("D:\Excelforum\ExcelForum office\excel tip old code\Shared Macro\23\23SampleData.xls", "Sample_Data")

'Calling function FillListBox  for adding items in List Box

'Assign List box object and tarray as parameter

FillListBox Me.ListBox1, tArray

'Releasing array variables and deallocate the memory used for their elements.

Erase tArray

End Sub

Private Sub FillListBox(lb As MSForms.ListBox, RecordSetArray As Variant)

'Filling List box lb with data from RecordSetArray

Dim r As Long, c As Long

With lb

.Clear

'Assigning value to listbox

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

'Selecting no item in the List box by default

.ListIndex = -1

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)

Dim dbConnection As ADODB.Connection, rs As ADODB.Recordset

Dim dbConnectionString As String

'Declaring a connection string and the driver require for establishing connection

dbConnectionString = "DRIVER={Microsoft Excel Driver (*.xls)};ReadOnly=1;DBQ=" & SourceFile

'Creating a new ADODB connection

Set dbConnection = New ADODB.Connection

On Error GoTo InvalidInput

'Open the database connection

dbConnection.Open dbConnectionString

'Getting the recordset from defined named range

Set rs = dbConnection.Execute("[" & SourceRange & "]")

On Error GoTo 0

'Returns a two dimensional array with all records in rs

ReadDataFromWorkbook = rs.GetRows

'Close the recordset and database connection

rs.Close

dbConnection.Close

Set rs = Nothing

Set dbConnection = Nothing

Exit Function

'Code for handling error

InvalidInput:

MsgBox "The source file or source range is invalid!", _

vbExclamation, "Get data from closed workbook"

End Function

'Add below code in UserForm1

Option Explicit

Private Sub CommandButton1_Click()

Dim name1 As String

Dim i As Integer

'Assign the selected value to variable name1

For i = 0 To ListBox1.ListCount - 1

If ListBox1.Selected(i) Then

name1 = ListBox1.Value

Exit For

End If

Next

'Unload the userform

Unload Me

'Display the selected name

MsgBox "You have selected " & name1 & "."

End Sub

Private Sub UserForm_Initialize()

Dim ListItems As Variant, i As Integer

Dim SourceWB As Workbook

'Turning screen updates off

Application.ScreenUpdating = False

With Me.ListBox1

'Remove existing entries from the listbox

.Clear

'Open the source workbook as ReadOnly

Set SourceWB = Workbooks.Open("D:\Excelforum\ExcelForum office\excel tip old code\Shared Macro\23\23SampleData.xls", _

False, True)

'Get the range of values you want

ListItems = SourceWB.Worksheets(1).Range("A2:A10").Value

'Close the source workbook without saving changes

SourceWB.Close False

Set SourceWB = Nothing

Application.ScreenUpdating = True

'Convert values to a vertical array

ListItems = Application.WorksheetFunction.Transpose(ListItems)

For i = 1 To UBound(ListItems)

'Populate the listbox

.AddItem ListItems(i)

Next i

'Selecting no items by default, set to 0 to select the first item

.ListIndex = -1

End With

End Sub

如果您喜欢此博客,请在Facebook和Facebook上与您的朋友分享。

我们希望收到您的来信,请让我们知道如何改善我们的工作并为您做得更好。写信给我们[email protected]