Excel VBA - using SELECT CASE but now need an array

前端 未结 1 1840
挽巷
挽巷 2020-12-21 16:43

I\'ve currently got the code below. There can only currently be seven values for \"ins\" and so the code suffices, however as of next month I have been told that there will

相关标签:
1条回答
  • 2020-12-21 17:22

    I would use a dictionary object for this. Here is a proof-of-concept based on your lines:

    Private Sub test()
        Dim i As Long
        Dim lr As Long
        Dim ins As String        
        Dim rngCases As Range, rngCases2 As Range, rngCase As Range
        Dim dicCases As Dictionary
    
        lr = Range("A" & Rows.Count).End(xlUp).Row
    
        ' rngCases stores the possible values of ins
        ' Here I assume they are stored in col 40
        Set rngCases = Range(Cells(6, 40), Cells(lr, 40))
    
        ' rngCases2 stores the values you want to map for each value of ins.
        ' Here I assume they are stored in col 41
        ' No of entries = No of entries of rngCases
        Set rngCases2 = Range(Cells(6, 41), Cells(lr, 41))
        Set dicCases = New Dictionary
    
        For Each rngCase In rngCases
            If Not dicCases.Exists(rngCase.Value) Then
                dicCases.Add Key:=rngCase.Value, Item:=rngCases2.Value
            End If
        Next rngCase
    
        For i = 6 To lr
        Select Case Cells(i, 20)
            Case Is = ""
                ins = Mid(Cells(i, 11), 14, 2)
                    Select Case Cells(i, 10)
                        Case "Inx", "ComInx"
                             Select Case Cells(i, 9)
                                 Case "EINX"
                                    ' We simply need to refer to the mapped value of ins
                                     If dicCases.Exists(ins) then
                                         Cells(i, 9) = dicCases.Item(ins)
                                     Else
                                         ' Throw an error or do something here
                                     End If
                             End Select
                    End Select
        End Select
        Next
    
    End Sub
    

    To enable the Dictionary, go to Tools->References and select Microsoft Scripting Runtime.

    I hope this gets you started!

    0 讨论(0)
提交回复
热议问题