vba基于大量可比对象的if语句,有什么更聪明的方法吗?

时间:2018-08-02 12:22:18

标签: 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 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”

like this:

'LCSPsum 2

                ElseIf (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) = LCSPnavn2 Then

                    Amount = Cells(k, 13)
                    LCSPsum2 = LCSPsum2 + Amount

'LCSPsum 3
                ElseIf (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) = LCSPnavn3 Then

                    Amount = Cells(k, 13)
                    LCSPsum3 = LCSPsum3 + Amount

一直到28 xD

它正在工作,但是我现在正尝试添加更多的“ buafd”,这是一个相当缓慢的过程,因为我必须添加7次“ cells(k,5)= buafd ...” 28次。

有人有一个聪明的解决方案,也可能使它更快地工作吗?

致谢 尼古拉斯

1 个答案:

答案 0 :(得分:1)

首先,我将变量放入数组中。这样,当您需要增加这些变量的数量时,就可以增加数组的大小。

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

这将是替换所有重复步骤的代码。如果此时仅使用金额,而您又不需要其他功能,则可以将其直接应用于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