[英]Create new range from 3 other column ranges in VBA Excel
I have 3 ranges in VBA: 我在VBA中有3个范围:
range1 = Range("A:A")
range2 = Range("B:B")
range3 = Range("C:C")
i want to return a new range where each row in the three ranges are added together. 我想返回一个新范围,其中三个范围中的每一行都加在一起。
So if I have the data 所以,如果我有数据
A, B, C
=========
1, 2, 3
2, 4, 5
1, 1, 2
where each of the 3 ranges only consist of the values (the column names are just to explain). 其中3个范围中的每一个仅由值组成(列名仅用于解释)。 So the first range has values 1, 2, 1, the second range has values 2, 4, 1, and the third range has values 3, 5, 2.
因此第一个范围的值为1,2,1,第二个范围的值为2,4,1,第三个范围的值为3,5,2。
I want to output the range consisting of 我想输出由...组成的范围
6
11
4
I guess it is something like 我猜它就像是
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
is this correct? 这个对吗?
Try like this: 试试这样:
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
Run MakeRanges
. 运行
MakeRanges
。 Pretty much, you receive a new column with the sum of the other columns. 差不多,您会收到一个新列,其中包含其他列的总和。 It is a good idea to change the ActiveSheet into something meaningful.
将ActiveSheet更改为有意义的内容是个好主意。 If you don't like the formula, you may uncomment the
rngCell.Value
in my code. 如果您不喜欢该公式,可以在我的代码中取消注释
rngCell.Value
。 The array you need is varResult
. 你需要的数组是
varResult
。 Remove the stop
and find a way to return it in a function. 删除
stop
并找到在函数中返回它的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.