如何在不使用VBA中的循环的情况下对列求和

时间:2019-05-27 06:12:23

标签: excel 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放慢速度。

有没有不使用循环即可实现此目标的简单方法?

3 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

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

答案 1 :(得分:0)

这是使用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 :(得分:0)

您已经有两个不错的答案,只想在这里加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