繁体   English   中英

在VBA Excel中从3个其他列范围创建新范围

[英]Create new range from 3 other column ranges in VBA Excel

我在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

这个对吗?

试试这样:

 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并找到在函数中返回它的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM