gpt4 book ai didi

Excel VBA - 使用 SELECT CASE 但现在需要一个数组

转载 作者:行者123 更新时间:2023-12-02 21:31:47 24 4
gpt4 key购买 nike

我目前得到了下面的代码。目前“ins”只能有 7 个值,因此代码就足够了,但是从下个月开始,我被告知将有超过 900 个值!

我假设我可以使用某种数组,而不是编写另外 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

最佳答案

我会为此使用字典对象。以下是基于您的台词的概念验证:

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

要启用字典,请转至工具->引用并选择Microsoft Scripting Runtime

我希望这能让您开始!

关于Excel VBA - 使用 SELECT CASE 但现在需要一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18311320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com