【问题标题】:Create new range from 3 other column ranges in VBA Excel在 VBA Excel 中从其他 3 个列范围创建新范围
【发布时间】:2017-02-02 10:23:03
【问题描述】:

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

这对吗?

【问题讨论】:

  • 为什么不直接使用 SUM 公式?
  • 这是一个更大的 vba 代码,我不能在工作表中找到总和,所以我必须在 VBA 中完成
  • 只要您的范围对齐并且大小相同,那么这种方法就非常好。
  • 我不需要标注 newRange 的尺寸吗?

标签: vba excel


【解决方案1】:

试试这样:

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

【讨论】:

  • 谢谢!但我无法填充 excel 表。我需要将范围保存在内存中并在函数中返回它
  • 我不明白。您只需要返回没有任何值的范围吗?还是这些值的数组 - 6,11,4?
  • 值 6、11 和 4 的数组。我只需要返回可以在 =SUM() 函数中使用的东西,所以如果我可以只使用普通数组,那么没关系
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-20
  • 1970-01-01
  • 2014-01-05
  • 2019-07-22
  • 1970-01-01
相关资源
最近更新 更多