【问题标题】:Comboboxes where in first one is list of the sheets and in second one is data from first column from selected sheet in first combobox组合框,其中第一个是工作表列表,第二个是来自第一个组合框中所选工作表的第一列的数据
【发布时间】:2021-08-09 17:03:26
【问题描述】:

我是 VBA 新手,在如何自动执行所有操作时遇到了一些问题。我有一个用于分析的活动表和 10 个数据表。由于分析的类型,我想使用组合框来选择数据进行分析。

我想:

  1. 在 activesheet 上使用 combobox1 来选择我从中读取数据的工作表。
  2. 使用组合框 2,其中是组合框 1 中所选工作表中第一列的名称列表。

示例:表 2-10 是国家/地区的名称,第 1 列是这些国家/地区的城市,其中包含与每个城市相关的数据。所以在 combobox1 中我选择 UK =sheet(4) ,然后在 combobox2 London= 单元格 A40 中。然后我计算 B40 x C40 /F40...

我开始喜欢:

Public Sub Worksheet_Activate()
    Dim x As Integer
    totalcountries = Sheets.Count
    For x = 2 To totalcountries
    Me.Combobox1.AddItem Sheets(x).Name
    Next x
End Sub

还有:

Sub selectcity()
    Sheets(1).combobox2.List = Sheets(4).Range("A2:A56").Value 
End Sub

我不知道如何连接它。谢谢。

【问题讨论】:

    标签: excel vba combobox


    【解决方案1】:

    我们可以使用与组合框相关的“事件”。

    我这里使用的方法是:

    (1 )当您单击 ComboBox1 时,它会填充除 ActiveSheet 之外的所有工作表的名称。您现在可以从下拉列表中选择所需的工作表。

    (2 )当您离开 ComboBox1 时(通过按 TAB),它会使用您在 ComboBox1 中选择的工作表中的城市名称填充 ComboBox2。

    我将 ActiveSheet 命名为“acSht”只是为了在此处进行解释。你可以用你的名字。如果您使用其他名称,请将“acSht”替换为您提供给 ActiveSheet 的名称。

    转到开发人员并单击“控件”部分下的“设计模式”。

    现在双击 ComboBox1。这将带您进入 Visual Basic 编辑器窗口。在出现的白色窗格中,您可以在顶部看到两个下拉框。从右上角的下拉框中选择“GotFocus”。

    使用以下代码。

    Private Sub ComboBox1_GotFocus()
    
    Worksheets("acSht").ComboBox1.Clear
    
    Dim ws As Worksheet
    
        For Each ws In ThisWorkbook.Worksheets
        
            If Not ws.Name = "acSht" Then ThisWorkbook.Worksheets("acSht").ComboBox1.AddItem ws.Name
            
        Next ws
        
    End Sub
    

    接下来从右上角的下拉框中选择“KeyDown”并使用以下代码。

    Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    
    Worksheets("acSht").ComboBox2.Activate
    
    If KeyCode = vbKeyTab Then
        Worksheets("acSht").ComboBox2.Clear
    
            Dim ws As Worksheet, rng As Range, wsName As String
            
            If Not ThisWorkbook.Worksheets("acSht").ComboBox1.Value = Empty Then
                wsName = ThisWorkbook.Worksheets("acSht").ComboBox1.Value
                Set ws = ThisWorkbook.Worksheets(wsName)
            Else
                Exit Sub
            End If
            
                For Each rng In ws.Range("A2", ws.Range("A" & Rows.Count).End(xlUp))
                
                    ThisWorkbook.Worksheets("acSht").ComboBox2.AddItem rng.Value
                
                Next rng
    End If
    
    End Sub
    

    【讨论】:

    • 如果你只想使用鼠标而不是标签,你会怎么做?
    • 使用 ComboBox1_LostFocus() 事件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2021-11-22
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    相关资源
    最近更新 更多