繁体   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