2013-08-19 173 views
2

我目前得到下面的代碼。 「ins」目前只能有7個值,所以代碼就足夠了,但是到下個月我就被告知會有超過900個值!Excel VBA - 使用SELECT CASE,但現在需要一個數組

我假設,而不是寫另外900個case語句,我可以使用某種數組。任何人都可以給我一個正確的方向推動嗎?

Private Sub test() 
Dim i As Long 
Dim lr As Long 
Dim ins As String 

lr = Range("A" & Rows.Count).End(xlUp).Row 

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" 
           Select Case ins 
            Case "LD" 
             Cells(i, 9).Value = "SR" 
            Case "GP" 
             Cells(i, 9).Value = "GAMA" 
            Case "AV" 
             Cells(i, 9).Value = "NU" 
            Case "AX" 
             Cells(i, 9).Value = "AXC" 
            Case "MZ" 
             Cells(i, 9).Value = "MZE" 
            Case "AD" 
             Cells(i, 9).Value = "AGD" 
            Case "AG" 
             Cells(i, 9).Value = "AG" 
           End Select 
        End Select 
      End Select 
End Select 
Next 

End Sub 
+1

有數組,集合,字典,自己的類型等等。研究! – 2013-08-19 10:34:53

+1

我建議你使用存儲在範圍硬編碼中的查找表,這些值將成爲維護噩夢 – JosieP

回答

5

我會用這個字典對象。這是根據你的線條證明了概念:

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 

要啓用Dictionary,去Tools->References並選擇Microsoft Scripting Runtime

我希望這能讓你開始!