如何使用不同的VBA组合框名称初始化字符串

时间:2019-07-08 16:36:54

标签: excel vba

在Excel中工作,我有10个工作表,每个工作表都具有相同的ActiveX组合框。组合框列出了工作簿中其他工作表的子集。

一旦在“组合框”中选择了一个工作表,则可以单击它旁边的按钮,该按钮运行一个宏,该宏将所选工作表中的数据填充到活动工作表中。

我的问题是,目前有一个模块可以通过引用组合框名称来初始化工作表名称,每个工作表(即ComboBox1至Combox10)上的名称都不同。

我现在正在做的是每次在具有此组合框的10张纸上的每张纸上运行宏时都更改组合框引用。不幸的是,我不能指望用户每次使用宏都会更新宏。

是否可以使用通配符在模块中编辑此组合框引用,或者有其他方法可以解决此问题?

我尝试将公共工作表添加到每个工作表的私有工作表中,但是随后遇到了400错误。我还尝试过在ComboBox(即ComboBox *)后加一个*,但这显然也不正确。

Sub FillTable()

Dim lastrow, lastrow2, i As Integer
Dim Searchfor, j, candnumArr, MarksArr As Variant
Dim wsName As String

    'Worksheet selected in Combobox which differs across worksheets
    ' This is the reference that needs to be changed from 1 to 2/3/etc
    wsName = ActiveSheet.ComboBox1.Text

    With Sheets(wsName)
        lastrow = .Cells(Rows.Count, "B").End(xlUp).Row
        candnumArr = Range(.Cells(6, 2), .Cells(lastrow, 14))
    End With

    'Arrays to be filled sheet
    With ActiveSheet
        lastrow2 = .Cells(Rows.Count, "H").End(xlUp).Row
        ' load variant array with search variables
        searcharr = Range(.Cells(6, 8), .Cells(lastrow2, 8))
        ' define an output aray
        PartNumArr = Range(.Cells(6, 13), .Cells(lastrow2, 13))
        MarksArr = Range(.Cells(6, 17), .Cells(lastrow2, 26))
    End With

    On Error Resume Next

    For i = 1 To lastrow2

        For j = 1 To lastrow
            Searchfor = searcharr(i, 1)
                If candnumArr(j, 1) = Searchfor Then
                    For kk = 1 To 13
                        PartNumArr(i, kk - 1) = candnumArr(j, kk)
                        MarksArr(i, kk - 2) = candnumArr(j, kk)
                    Next kk
                    Exit For
                End If

        Next j

    Next i

    ' writeout the output arrays
    With ActiveSheet
            Range(.Cells(6, 13), .Cells(lastrow2, 13)) = PartNumArr
            Range(.Cells(6, 17), .Cells(lastrow2, 26)) = MarksArr
    End With

End Sub

虽然代码适用于第一张工作表并使用其组合框,但我对如何更改它一无所知,因此它可以在具有此组合框的所有10张工作表中使用。

1 个答案:

答案 0 :(得分:0)

ActiveX元素的名称在多个工作表中可以相同,因此可以将它们命名为相同的名称。

如果它是ActiveX控件,则可以使用以下3种方法之一(甚至更多):

Sub testBox()
    Dim ws As Worksheet

    For Each ws In ActiveWorkbook.Worksheets

        'If they have the same name
        Debug.Print ws.OLEObjects("ComboBox1").Object.Value

        'If you only have one ActiveX object per Page
        Debug.Print ws.OLEObjects(1).Object.Value

        'If you want to loop it and check by name....
        Dim cb As OLEObject
        For Each cb In ws.OLEObjects
            If Left(cb.Name, 8) = "ComboBox" Then Debug.Print cb.Object.Value
        Next cb

    Next ws
End Sub

该示例或多或少直接取自 Microsoft官方文档! https://docs.microsoft.com/en-us/office/vba/excel/concepts/controls-dialogboxes-forms/using-activex-controls-on-sheets