我想缩短我的重复代码,它有许多这些行:
.Range("AB81") = "=VLOOKUP(I65,'[" & R1 & "]" & "Investments" & "'! $B$58:$F$81," & 5 & ",0)"
.Range("AD81") = "=VLOOKUP(K65,'[" & R1 & "]" & "Investments" & "'! $B$58:$F$81," & 5 & ",0)"
.Range("AF81") = "=VLOOKUP(M65,'[" & R1 & "]" & "Investments" & "'! $B$58:$F$81," & 5 & ",0)"
.Range("AH81") = "=VLOOKUP(O65,'[" & R1 & "]" & "Investments" & "'! $B$58:$F$81," & 5 & ",0)"
.Range("AJ81") = "=VLOOKUP(Q65,'[" & R1 & "]" & "Investments" & "'! $B$58:$F$81," & 5 & ",0)"
.Range("AL81") = "=VLOOKUP(S65,'[" & R1 & "]" & "Investments" & "'! $B$58:$F$81," & 5 & ",0)"
.Range(..81)
范围每次移动2列,VLOOKUP
公式中的第一个范围也是如此。
答案 0 :(得分:2)
一次设置所有公式时,相对引用会自动调整:
.Range("AB81,AD81,AF81,AH81,AJ81,AL81").Formula = _
"=VLOOKUP(I65,'[" & R1 & "]" & "Investments" & "'!$B$58:$F$81," & 5 & ",0)"
答案 1 :(得分:1)
尝试使用For循环,步长为2(因为每行跳2列)。然后使用Offset
命令将公式范围和内部范围每次增加2列:
Dim ofst As Long
For ofst = 0 To 10 Step 2
.Range("AB81").Offset(0,ofst).Formula = _
"=VLOOKUP(" & .Range("I65").Offset(0,ofst).Address & ",'[" & R1 & "]" & "Investments" & "'! $B$58:$F$81," & 5 & ",0)"
Next ofst
答案 2 :(得分:0)
我一直坚决反对编写代码来插入公式。这就像要求机械师取一个机械师修理汽车一样。因此,以下代码将结果写入每个单元格而不是公式。但如果它是你必须拥有的公式,它可以使用在这里构造循环时使用的相同逻辑进行修改。
List<DonateTable> top15Elements = data.subList(0,15);