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