vba基于大量可比数据的大型if语句,有更聪明的方法吗?
我有一个相当大的代码,它一开始很小,但随着变量的不断出现,代码也随之出现 我的第一个“问题”是这一部分:vba基于大量可比数据的大型if语句,有更聪明的方法吗?,vba,if-statement,optimization,Vba,If Statement,Optimization,我有一个相当大的代码,它一开始很小,但随着变量的不断出现,代码也随之出现 我的第一个“问题”是这一部分: If (Cells(k, 5) = buafd1 Or Cells(k, 5) = buafd2 Or Cells(k, 5) = buafd3 _ Or Cells(k, 5) = buafd4 Or Cells(k, 5) = buafd5 Or Cells(k, 5) = buafd6 Or Cells(k, 5) = buafd7 _ Or Cells(k, 5) = buafd8
If (Cells(k, 5) = buafd1 Or Cells(k, 5) = buafd2 Or Cells(k, 5) = buafd3 _
Or Cells(k, 5) = buafd4 Or Cells(k, 5) = buafd5 Or Cells(k, 5) = buafd6 Or Cells(k, 5) = buafd7 _
Or Cells(k, 5) = buafd8 Or Cells(k, 5) = buafd9 Or Cells(k, 5) = buafd10 Or Cells(k, 5) = buafd11 _
Or Cells(k, 5) = buafd12 Or Cells(k, 5) = buafd13) And Cells(k, 6) = LCSPnavn1 Then
Amount = Cells(k, 13)
LCSPsum1 = LCSPsum1 + Amount
正如你所看到的,我所看到的单元格是相同的,但我正在对照变量列表检查它,这是激活求和函数的标准
下一件事是我有很多“LCSPsums”
一直到28 xD
这是工作,但我现在试图把更多的“buafd”,这是一个相当缓慢的过程,因为我必须添加7次“细胞(k,5)=buafd…”28次
是否有人有一个智能的解决方案,也可以使它工作得更快
问候
Niklas首先,我将把变量放入一个数组中。这样,当需要增加这些变量的数量时,只需增加数组的大小即可
Dim oBuafd(12) As String
Dim oLCSPnavn(27) As Double
Dim oLCSPsum(27) As Double ' or you could do a multi-dimensional array with oLCSPnavn
函数搜索数组并在找到值时返回true
Private Function InList(ByVal SearchValue As String, ByRef List() As String) As Boolean
InList = False
Dim oCounter As Integer
For oCounter = 0 To UBound(List)
If StrComp(SearchValue, List(oCounter), vbTextCompare) = 0 Then
InList = True
Exit For
End If
Next
End Function
这将是替换所有重复步骤的代码。如果此时正在使用amount,并且没有其他功能,那么您不需要它,您可以直接将amount应用于oLCSPnavn
Dim Amount As Double
Dim oCounter As Integer
For oCounter = 0 To UBound(oLCSPnavn)
If InList(Sheet1.Cells(11, 5), oBuafd) And oLCSPnavn(oCounter) = Sheet1.Cells(11, 6) Then
Amount = Sheet1.Cells(11, 13)
oLCSPsum(oCounter) = oLCSPsum(oCounter) + Amount ' Is this all your doing with amount or does it have another purpose?
End If
Next
编辑:缺少oLCSPsum数组,最初将其读取为oLCSPnavn。添加了sum声明,并将其放在代码中的适当位置,所以第一个问题是当我将变量声明为字符串时,如:Dim LCSPnavn(1到100),然后尝试将其设置为:LCSPnavn1=单元格(i,12),然后我得到未定义的错误变量,怎么办?@NiklasBorkPetersen它将是LCSPnavn(1)=单元(i,12)。这里有一篇关于这个问题的短文。另外请注意:如果您的数组索引起始值为1,则还需要更新计数器以启动它们的索引。
Dim Amount As Double
Dim oCounter As Integer
For oCounter = 0 To UBound(oLCSPnavn)
If InList(Sheet1.Cells(11, 5), oBuafd) And oLCSPnavn(oCounter) = Sheet1.Cells(11, 6) Then
Amount = Sheet1.Cells(11, 13)
oLCSPsum(oCounter) = oLCSPsum(oCounter) + Amount ' Is this all your doing with amount or does it have another purpose?
End If
Next