在VBA中跨多个子目录使用字典

问题描述 投票:0回答:1

我有一个在一个子集中定义的字典,我想用它从不同子集中的键中获取值。

Private Sub CommandButton2_Click()

ID = Me.TextBox1.Value
Dim rwd As Worksheet
Set rwd = ThisWorkbook.Sheets("Raw Data")


If Application.WorksheetFunction.CountIf(summ.Range("A:A"), Me.TextBox4.Value) > 0 Then
    Dim rowsDict As Object
    Set rowsDict = CreateObject("Scripting.Dictionary")
    Dim counter As Long
    counter = 1
    For i = 2 To rwd.Range("A" & Application.rows.Count).End(xlUp).Row
        If rwd.Range("A" & i).Value = ID Then
            RowAndNumber = CStr(counter) & "-" & (rwd.Range("J" & i).Value)
            Me.ComboBox3.AddItem (RowAndNumber)
            rowsDict.Add RowAndNumber, i '
            counter = counter + 1
        End If
    Next
End Sub

Private Sub ComboBox3_Change()

    n = rowsDict.Item(Me.ComboBox3.Value)
    Me.bTextBox131.Value = rwd.Range("J" & n).Value
End Sub
excel vba excel-vba userform
1个回答
3
投票

您需要在模块范围内声明字典

' Move your declaration to outside your Sub
Dim rowsDict As Object
Private Sub CommandButton2_Click()
    ID = Me.TextBox1.Value
    Dim rwd As Worksheet
    Set rwd = ThisWorkbook.Sheets("Raw Data")

    If Application.WorksheetFunction.CountIf(summ.Range("A:A"), Me.TextBox4.Value) > 0 Then
        Set rowsDict = CreateObject("Scripting.Dictionary")
        Dim counter As Long
        counter = 1
        For i = 2 To rwd.Range("A" & Application.rows.Count).End(xlUp).Row
            If rwd.Range("A" & i).Value = ID Then
                RowAndNumber = CStr(counter) & "-" & (rwd.Range("J" & i).Value)
                Me.ComboBox3.AddItem (RowAndNumber)
                rowsDict.Add RowAndNumber, i '
                counter = counter + 1
            End If
        Next
    ' You're also missing an End If
    End If
End Sub

Private Sub ComboBox3_Change()
    n = rowsDict.Item(Me.ComboBox3.Value)
    Me.bTextBox131.Value = rwd.Range("J" & n).Value
End Sub
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.