簡體   English   中英

如何在不使用VBA中的循環的情況下對列求和

[英]How to sum columns without using Loop in VBA

我正在嘗試重新格式化報告,以便可以將其輸入到我的系統中,如下所示:

wbOutput.Sheets(1).Range("B" & O_lrow + 1 & ":B" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("F1:F" & lRow).Value

我遇到的一個問題是F列必須是兩個源列的總和,而下面的列不起作用:

wbOutput.Sheets(1).Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("N1:N" & lRow).Value + wbSource.Sheets(1).Range("O1:O" & lRow).Value

我試圖避免使用循環,因為有很多行,而且我不希望marco減慢太多。

有沒有不使用循環即可實現此目的的簡單方法?

您可以嘗試以下方法:

 wbOutput.Sheets(1).Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow).Value = _ 
             wbSource.Sheets(1).Evaluate("N1:N" & lRow & " + O1:O" & lRow)

這是使用Application.Sum函數的一種方法:

Option Explicit
Sub SumTest()

    Dim SumA As Range
    Dim SumB As Range

    With wbSource.Sheets(1)
        Set SumA = .Range("N1:N" & lRow)
        Set SumB = .Range("O1:O" & lRow)
    End With

    wbOutput.Sheets(1).Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow) = Application.Sum(SumA, SumB)

End Sub

您已經有兩個不錯的答案,只想在這里加2美分...

如果您有大量數據,則應考慮使用數組,而要實現的目標之一就是以下方法,請參見注釋以獲取更多詳細信息:

Dim wsOutput As Worksheet: Set wsOutput = wbOutput.Sheets(1) 'allocate the output worksheet to a variable
Dim wsSource As Worksheet: Set wsSource = wbSource.Sheets(1) 'allocate the source worksheet to a variable

Dim arrSource As Variant
Dim arrOutput() As Variant 'Could change this to match your expected data type output
Dim R As Long, C As Long
arrSource = wsSource.Range("N1:O" & lRow) 'Get the source data into an array
ReDim arrOutput(1 To UBound(arrSource), 1 To 1) 'set the size of the output
For R = 1 To UBound(arrSource)
    For C = 1 To UBound(arrSource, 2)
        arrOutput(R, 1) = arrSource(R, 1) + arrSource(R, 2) 'make your calculations here
    Next C
Next R

wsOutput.Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow) = arrOutput 'spit it back to the sheet once is done

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM