我在VBA中有3个范围:
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
这是正确的吗?
答案 0 :(得分:0)
试试这样:
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
并找到在函数中返回它的方法。