2010-10-20 59 views
1

我有一句話下面的代碼2007的宏在那裏我填寫客戶名稱的下拉從Excel電子表格填充一個下拉列表,然後在下拉改變填充相關領域(VBA)文本框

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 

因此,我有一個客戶名稱列,我創建了一個命名範圍(客戶),它填充下拉列表。但是,當我在下拉列表中選擇一個客戶時,我想填充兩個地址字段(1街道,2個城市)客戶的地址。

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

該電子表格有大約10列,第一位是客戶,第九位是地址1,最後一位是地址2。我如何使用變量客戶填充地址字段?我是否必須創建一個新的命名範圍,並且有類似 從myRange中選擇customer,address1,address2 where customer = customerName?

+0

爲您添加了一些更新。 – ocodo 2010-10-20 04:58:05

回答

0

你自己回答了這個問題,創建一個列您的需要命名的範圍,然後做選擇:

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

到一個新的記錄集,並從項目0地址字段它。

+0

哇,我甚至沒有嘗試過,沒想到會起作用。但是,如果我有查詢rsT.Open「選擇客戶,郵政編碼,州,國家從客戶」,cn,adOpenStatic我如何填充例如文本框CompanyName.Value =客戶名?嘗試這次做CompanyName.Value =客戶,但它沒有工作 – Morgan 2010-10-20 04:10:10

+0

'cbo_customer.Value'是否不爲客戶返回正確的值? – ocodo 2010-10-20 04:13:27

+0

我忘了那裏的WHERE語句(太興奮了)rsT.Open「SELECT Customer,Postcode,State,Country FROM Customers WHERE Customer =」+ customerName,cn,adOpenStatic雖然引發了一個錯誤,但我並不習慣於VBA語法,我應該如何糾正查詢語句? – Morgan 2010-10-20 04:17:59