语法帮助Excel脚本VB

时间:2015-10-20 08:47:42

标签: excel vba excel-vba

我正在检查来自A3和向下的单元格是否为空,然后我想将一个公式放到单元格E4中,直到找到一个空的A单元格。

我正在尝试的脚本就是这个:

Sub avg()
Dim dat As Variant
Dim rng As Range
Dim i As Long
i = 3

Set rng = Range("A3:A10")
dat = rng
For i = LBound(dat, 1) To UBound(dat, 1)
    If dat(i, 1) <> "" Then
        rng(i + 1, 5).FormulaR1C1 = "=wwAggregate(""KOSTAS-PC"", Data!R3C1,""Res1000"",'5min REPORT'!R3C1,'5min REPORT'!R4C1,""AVG"","""")"
    End If
Next
End Sub

我的问题在于公式行,我需要动态地改变'5min REPORT'!R3C1到'5min REPORT'!R3Ci和'5min REPORT'!R4C1到'5min REPORT'!R3Ci + 1.

我用&amp; i尝试了这个,但我得到的是一个字符串“R3C&amp; i”而不是“R3C3”等

"=wwAggregate(""KOSTAS-PC"", Data!R3C1,""Res1000"",'5min REPORT'!R3C&i,'5min REPORT'!R4C&i+1,""AVG"","""")"

我迷失了所有这些“”

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

要用R3C i替换R3C1(即计数器变量的当前值,请尝试

For i = LBound(dat, 1) To UBound(dat, 1)
    If dat(i, 1) <> "" Then
        rng(i + 1, 5).FormulaR1C1 = "=wwAggregate(""KOSTAS-PC"", Data!R3C " & i & ",""Res1000"",'5min REPORT'!R3C" & i & ",'5min REPORT'!R4C1,""AVG"","""")"
    End If
Next

本文中的语法高亮显示了字符串和变量的不同之处。

我注意到最后一个单元格引用仍然是R4C1。您可能还需要将该列引用调整为i变量。很难说没有上下文。

请记住,在VBA中,如果它在字符串中,则需要复制双引号。如果双引号需要位于字符串的开头或结尾,则需要将其重复三次。当i = 7时,上面的公式将返回

=wwAggregate("KOSTAS-PC", Data!R3C7,"Res1000",'5min REPORT'!R3C7,'5min REPORT'!R4C1,"AVG","")