2015-01-01 20 views
0

我最近創建了一個工作簿,其中包含帶有組合框的用戶窗體,名稱爲「combobox1」 我有一個代碼,它將範圍爲「B2:B .. ..「 現在我想讓它如何在一個組合框中的另一列shuld帶來來自同一目錄的數據,但範圍爲exp:」A1:A ....「 我需要你的幫助 thx 。vba使用外部數據的兩列組合框

[Private Sub UserForm_Initialize() 

`Dim ListItems As Variant, i As Integer 
`Dim SourceWB As Workbook 
With Me.ComboBox1 
.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:\Users\Mohsen\Desktop\new prj\Data base\partlist.xls", _ 
False, True) 
ListItems = SourceWB.Worksheets(1).Range("B2:B1468").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 

回答

0

你的問題並不清楚,其中數據的第二列應來自所以我假定第一組合框列是從SourceWB,Sheet 1中,B列和所述第二組合框列是從相同片在列B左側的列中。您可以更改這些以適應。

我也編碼識別列B中的最後一個數據行。這將防止不必要地搜索1468行。再次,如果這沒有幫助,請更改。

Option Explicit 
Private Sub UserForm_Initialize() 
Dim ListItems As Variant 
Dim i As Integer 
Dim SourceWB As Workbook 
Dim listVal As Range 
Dim srcLastRow As Long 

'for testing purposes 
Dim srcName As String 
srcName = "C:\Users\Mohsen\Desktop\new prj\Data base\partlist.xls" 

    With Me.ComboBox1 
     'Set the number of columns by code 
     .ColumnCount = 2 
     .Clear 
     Application.ScreenUpdating = False 
     Set SourceWB = Workbooks.Open(srcName, False, True) 
      'find the last row of data to prevent searching 1468 rows unnecessarily 
      srcLastRow = SourceWB.Sheets(1).Cells(Rows.Count, "B").End(xlUp).Row 
      For Each listVal In SourceWB.Sheets(1).Range("B2:B" & srcLastRow) 
       .AddItem listVal.Value 
       'Offset(0,-1) gets second column of data from cell to the left 
       .List(.ListCount - 1, 1) = listVal.Offset(0, -1).Value 
      Next listVal 
     SourceWB.Close False 
     Set SourceWB = Nothing 
     Application.ScreenUpdating = True 
     .ListIndex = -1 
    End With 
End Sub 

查看Combobox1的屬性窗口,瞭解可能需要在代碼中設置的其他屬性。

+0

非常感謝你的回答,非常有用。我已經將combobox值鏈接到了範圍「C9」,並且它將左列值返回給C9,並且它的OK,現在我想將第二列(右側)鏈接到exp「B9」的單元格,並且我想要用於設置兩個鏈接值的VBA代碼。 –