2015-01-01 21 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代码。 –