Excel vba:根据A列中的单元格获取B列上的单元格范围

时间:2016-01-12 15:31:23

标签: excel vba excel-vba combobox


我有一个vba脚本,可以从所有工作表中获取信息,将它们添加到不同的组合框中,每当从组合框中选择一个值时,会发生不同的事情。
我填写的第一个组合如下:

Private Sub Workbook_Open()

Dim oSheet As Excel.Worksheet
Dim oCmbBox As MSForms.ComboBox
Set oCmbBox = ActiveWorkbook.Sheets(1).cmbSheet
oCmbBox.Clear
For Each oSheet In ActiveWorkbook.Sheets
    If oSheet.Index > 1 Then
        oCmbBox.AddItem oSheet.Name
    End If
Next oSheet

End Sub

第二个组合框正在执行以下操作:

Private Sub cmbSheet_Change()

Dim oSheet As Excel.Worksheet

'Report combo box
Dim oCmbBox As MSForms.ComboBox
Set oCmbBox = ActiveWorkbook.Sheets(1).cmbSheet

'Tech combo box
Dim tCmbBox As MSForms.ComboBox
Set tCmbBox = ActiveWorkbook.Sheets(1).techCombo
tCmbBox.Clear

Dim rng As Range
Set rng = Sheets(oCmbBox.Value).Range("A2:A10")
For Each cell In rng
    If Not IsEmpty(cell.Value) Then
        tCmbBox.AddItem cell.Value
    End If
Next cell

ActiveWorkbook.Sheets(1).techCombo.ListIndex = 0
End Sub

我有以下表格:
sheet

现在,从techCombo(即Teknik_1)中选择一个值我希望第三个组合框填充B6 - B9范围内的数据。
这可能吗?
提前谢谢!

2 个答案:

答案 0 :(得分:2)

鉴于您提供的示例数据,这样的事情应该适合您。请注意,此代码位于Sheet1代码模块中:

Private Sub techCombo_Change()

    Dim ws As Worksheet
    Dim rFound As Range
    Dim cbo3 As ComboBox

    Set cbo3 = Me.ComboBox3 'Change to the actual name of the third combobox

    cbo3.Clear

    With Me.cmbSheet
        If .ListIndex = -1 Then Exit Sub    'Nothing selectd in cmbSheet
        Set ws = ActiveWorkbook.Sheets(.Text)
    End With

    With Me.techCombo
        If .ListIndex = -1 Then Exit Sub    'Nothing selected in techCombo
        Set rFound = ws.Columns("A").Find(.Text, ws.Cells(ws.Rows.Count, "A"), xlValues, xlWhole)
    End With

    If Not rFound Is Nothing Then
        If Trim(Len(rFound.Offset(2, 1).Text)) = 0 Then
            cbo3.AddItem rFound.Offset(1, 1).Value
        Else
            cbo3.List = ws.Range(rFound.Offset(1, 1), rFound.Offset(1, 1).End(xlDown)).Value
        End If
    End If

End Sub

答案 1 :(得分:0)

Private Sub ComboBox21_Change() Dim TeckCMBxIndex TeckCMBxIndex = ActiveWorkbook.Sheets(3).ComboBox21.ListIndex Select Case TeckCMBxIndex Case 0 ActiveWorkbook.Sheets(3).ComboBox22.Clear Exit Sub Case 1 Set rng = Worksheets("SHEET3").Range("B6:B10") Case 2 Set rng = Worksheets("SHEET3").Range("B11:B15") End Select ActiveWorkbook.Sheets(3).ComboBox22.Clear For Each cell In rng If Not IsEmpty(cell.Value) Then ComboBox22.AddItem cell.Value End If Next cell End Sub

希望这应该对你有所帮助......我尝试了它并且它起作用了。请注意,我在sheet3中有值和组合框。