我有一个很大的代码,开始时很小,但是随着变量不断到来,代码也是如此。

我的第一个“问题”是这一部分:

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次。

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

问候
尼克拉斯

最佳答案

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

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

10-08 01:04