在VBA Excel中创build3个其他列范围的新范围

我有3个范围在VBA:

range1 = Range("A:A") range2 = Range("B:B") range3 = Range("C:C") 

我想返回一个新的范围,三个范围中的每一行都被添加在一起。

所以,如果我有数据

 A, B, C ========= 1, 2, 3 2, 4, 5 1, 1, 2 

其中3个范围中的每一个只包含这些值(列名仅仅是为了解释)。 因此,第一个范围的值为1,2,1,第二个范围的值为2,4,1,第三个范围的值为3,5,2。

我想输出由…组成的范围

 6 11 4 

我想这是类似的东西

 Dim newRange As Range Dim RowNo As Long // make newRange as long as one of the other ranges For Each RowNo in LBound(newRange) newRange(RowNo).Value = range1(RowNo).Value + range2(RowNo).Value + range3(RowNo).Value Next RowNo // return newRange 

它是否正确?

尝试像这样:

  Option Explicit Public Sub MakeRanges() Dim lngCounterLeft As Long Dim lngCounterDown As Long Dim lngCounter As Long Dim rngCell As Range Dim varResult As Variant lngCounterDown = last_row(ActiveSheet.Name) lngCounterLeft = last_col(ActiveSheet.Name) ReDim varResult(0) For lngCounter = 1 To lngCounterDown Set rngCell = ActiveSheet.Cells(lngCounter, lngCounterLeft + 1) rngCell.FormulaR1C1 = "=SUM(RC[-" & lngCounterLeft & "]:RC[-1])" 'rngCell.Interior.Color = vbRed If lngCounter > 1 Then ReDim Preserve varResult(UBound(varResult) + 1) End If varResult(UBound(varResult)) = rngCell.Value rngCell.Clear Next lngCounter Stop End Sub Public Function last_row(Optional str_sheet As String, Optional column_to_check As Long = 1) As Long Dim shSheet As Worksheet If str_sheet = vbNullString Then Set shSheet = ThisWorkbook.ActiveSheet Else Set shSheet = ThisWorkbook.Worksheets(str_sheet) End If last_row = shSheet.Cells(shSheet.Rows.Count, column_to_check).End(xlUp).Row End Function Public Function last_col(Optional str_sheet As String, Optional row_to_check As Long = 1) As Long Dim shSheet As Worksheet If str_sheet = vbNullString Then Set shSheet = ActiveSheet Else Set shSheet = Worksheets(str_sheet) End If last_col = shSheet.Cells(row_to_check, shSheet.Columns.Count).End(xlToLeft).Column End Function 

运行MakeRanges 。 非常多的,你会收到一个新的列与其他列的总和。 将ActiveSheet改为有意义的是一个好主意。 如果你不喜欢公式,你可以在我的代码中取消注释rngCell.Value 。 你需要的数组是varResult 。 删除stop并find一种方法来返回一个函数。