在excel中的列中填充单词下拉列表,然后在下拉列表中填充带有相关字段(VBA)的文本框

时间:2010-10-20 03:47:04

标签: excel vba ms-word

我在单词2007宏中有以下代码,我在excel电子表格中填写了一个带有客户名称的下拉列表

Private Sub UserForm_Initialize()
Dim i As Integer
Dim cn As ADODB.Connection
Dim rsT As New ADODB.Recordset
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=CCustomers.xls;Extended Properties=Excel 8.0;"
.CursorLocation = adUseClient
.Open
End With
rsT.Open "Select distinct * from Customer", cn, adOpenStatic

i = 0

With rsT
' This code populates the combo box with the values
' in the YourNamedRange named range in the .xls file. this exampletable is 2 rows by 6 columns and is set as a named range.

Do Until .EOF
ComboBox_Company.AddItem (i)
ComboBox_Company.Column(0, i) = rsT.Fields(0).Value
.MoveNext
i = i + 1
Loop
End With
End Sub

所以我有一个包含客户名称的列,我创建了一个命名范围(Customer),并填充了下拉列表。但是,当我在下拉列表中选择客户时,我想用(1街道,2个城市)填写客户地址的两个地址字段。

Private Sub cbo_customer_Change()
            Dim customerName As String
            customerName = cbo_customer.Value
End Sub

电子表格大约有10列,第一列是Customer,第9列是address1,最后一列是address2。如何使用变量customer填充地址字段?我是否必须创建一个包含所有字段的新命名范围,并具有类似的功能 从myRange中选择customer,address1,address2,其中customer = customerName?

1 个答案:

答案 0 :(得分:0)

您自己回答了这个问题,使用您需要的列创建一个命名区域,然后执行选择:

"SELECT customer, address1, address2 FROM NewRange WHERE customer = '" & customerName & "'"

进入新的记录集,并从中获取项目0中的地址字段。