excel - 如何以行号作为变量循环遍历特定范围?

标签 excel vba loops

我有一堆公式适用于我数据中的特定(非连续)范围。有没有办法用数组和/或循环在更少的行中做到这一点?

.Range("R" & RowA).FormulaR1C1 = "=RC[-1]"
.Range("W" & RowA).FormulaR1C1 = "=(RC[-5]*RC[-7])+RC[-2]"
.Range("Y" & RowA).FormulaR1C1 = "=RC[-12]*RC[-2]"

.Range("R" & RowB).FormulaR1C1 = "=RC[-1]"
.Range("W" & RowB).FormulaR1C1 = "=(RC[-5]*RC[-7])+RC[-2]"
.Range("Y" & RowB).FormulaR1C1 = "=RC[-12]*RC[-2]"

.Range("R" & RowC).FormulaR1C1 = "=RC[-1]"
.Range("W" & RowC).FormulaR1C1 = "=(RC[-5]*RC[-7])+RC[-2]"
.Range("Y" & RowC).FormulaR1C1 = "=RC[-12]*RC[-2]"

最佳答案

我会将行存储在一个数组中,然后使用Union 将所有行收集到一个变量中,并将其与每一列Intersect

这样您就可以一次访问特定列的所有已定义行。

Option Explicit

Public Sub example()
    Dim RowArr() As Variant
    RowArr = Array(1, 3, 17) 'define your rows here
    
    Dim AllRows As Range
        
    With ActiveSheet
        Dim Row As Variant
        For Each Row In RowArr
            If AllRows Is Nothing Then
                Set AllRows = .Rows(Row)
            Else
                Set AllRows = Union(AllRows, .Rows(Row))
            End If
        Next Row
        
        'write in all rows of a specific column
        Intersect(.Columns("R"), AllRows).FormulaR1C1 = "=RC[-1]"
        Intersect(.Columns("W"), AllRows).FormulaR1C1 = "=(RC[-5]*RC[-7])+RC[-2]"
        Intersect(.Columns("Y"), AllRows).FormulaR1C1 = "=RC[-12]*RC[-2]"
    End With
End Sub

除了循环你还可以这样写:

Set AllRows = .Range("1:1,3:3,17:17")

喜欢

Option Explicit

Public Sub example()
    With ActiveSheet
        Dim AllRows As Range
        Set AllRows = .Range("1:1,3:3,17:17")
        
        'write in all rows of a specific column
        Intersect(.Columns("R"), AllRows).FormulaR1C1 = "=RC[-1]"
        Intersect(.Columns("W"), AllRows).FormulaR1C1 = "=(RC[-5]*RC[-7])+RC[-2]"
        Intersect(.Columns("Y"), AllRows).FormulaR1C1 = "=RC[-12]*RC[-2]"
    End With
End Sub

但这只适用于少量的行。如果你有更多,你需要使用 Union

关于excel - 如何以行号作为变量循环遍历特定范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68496049/

相关文章:

excel - 编译错误: Syntax Error caused by code inserting a excel formula

c# - 如何最好地使用 VSTO 从 excel 中获取单元格值?

excel - 如何在 VBA 中使用 OFFSET 工作表函数?

c - 如何释放指向指针的指针,以便释放其中的所有元素?

python - 在循环中创建变量并在 Python 中初始化它们

Java Velocity循环在每3个项目周围添加div

python - 如何生成嵌入图表的 Excel 电子表格?

excel - 将一维数组(变体类型)转换为一维数组(字节类型)

excel - 使用 VBA 求解九个未知变量方程的蛮力法

arrays - VBA 数组逆运算