如何在VBA中的countif公式中插入变量?

时间:2016-02-16 11:32:58

标签: vba excel-vba countif excel

我正在尝试使用COUNTIFmcol作为变量来执行mrow功能。 它完美有效,问题出现了,我需要将每次mrow值增加1,但=COUNTIF(Analysis!RC[9]:R[8]C[9],""<=3"")中的行范围R []每次增加9。

我正在考虑将COUNTIF另一个变量ifor放入i = i + 9,但我不确定如何修复它。 有人可以帮忙吗?

Sub Test()
    Set wb = Workbooks("Book1.xlsm")
    Application.ScreenUpdating = False

    LastRow0 = Sheets("Tests").Range("A" & Sheets("Tests").Rows.Count).End(xlUp).Row

    mcol = 3

    For mrow = 2 To LastRow0
        Cells(mrow, mcol + 1) = "=COUNTIF(Analysis!RC[9]:R[8]C[9],""<=3"")"
        Cells(mrow, mcol + 2) = "=COUNTIF(Analysis!RC[9]:R[8]C[9],""good"")"
    Next mrow

End Sub

1 个答案:

答案 0 :(得分:0)

It is not clear to me what you want to increase by how much. That will not be a big programming problem, so I leave that to you. I'll show how to construct the formula using variables.

You create the formula as a string, so you will use string operations to construct it.

Dim s As String                   ; for the demo, this receives the formula string
Dim i As Integer, j As Integer    ; these are the variables we will use
....                              ; use them in loops, increment them as you need
s = "=COUNTIF(Analysis!RC[" & Trim(Str(i)) & "]:R[" & Trim(Str(j)) & "]C[" & Trim(Str(i)) & "],""<=3"")"

The Str function converts an integer to a string. The Trim function removes the leading space that Str put there.

Hope this helps.