如何循环表范围并输入具有多个变量的函数?

问题描述 投票:0回答:1

我有一个使用 CountIfs 公式填充的表。我想将此过程编码到 VBA 中,而不必编写每个单元格的公式。我可以使用 WorksheetFunction.CountIfs 来自动执行单个结果,但我无法将其编码到循环中。我希望该函数引用 A 列(关联)中的变量以及第 2 行中的日期。

这是我尝试填充的表,它在工作簿中定义为“TC_Month”:

enter image description here

这是我到目前为止的代码部分:

`Sub ConstData()

Dim wb As Workbook
Set wb = ThisWorkbook
Dim BD As Worksheet
Set BD = wb.Sheets("BuiltData")
Dim YD As Worksheet
Set YD = wb.Sheets("YearData")
Dim MD As Worksheet
Set MD = wb.Sheets("MonthData")

MD.Activate

Dim CurrentMonth As Date
CurrentMonth = DateSerial(Year(Date), Month(Date), 1)

Dim wk1 As Date
wk1 = CurrentMonth
Dim wk2 As Date
wk2 = DateAdd("d", 7, wk1)
Dim wk3 As Date
wk3 = DateAdd("d", 14, wk2)
Dim wk4 As Date
wk4 = DateAdd("d", 21, wk3)
Dim wk5 As Date
wk5 = DateAdd("d", 28, wk4)

With MD.Range("TC_Month")
.Cells(2, 2).Value2 = wk1
.Cells(2, 3).Value2 = wk2
.Cells(2. 4).Value2 = wk3
.Cells(2, 5).Value2 = wk4
.Cells(2, 6).Value2 = wk5
End With

With MD.Range("TC_Month")
Dim i As Integer
i = 3
Do Until i = 7
.Cells(i, 2).Value2 = WorksheetFunction.CountIfs(BD.Range("AF:AF"), _
MD.Range("TC_Month").Cells(i, 1), BD.Range("R:R"), ">250", _ 
BD.Range("AK:AK"), ">=" & CLng(wk1), BD.Range("AK:AK"), _
"<" & CLng(wk2))
i = i + 1
Loop
End With`

如果我使用实际的单元格引用,这个函数就可以工作。使用整数和循环时,此代码会导致 Excel 冻结或出现错误。它也只是为表格的第一列设置的,我无法理解日期如何可变以及计算附加列。

如果可能,我希望您能帮助我调整此代码和函数以适用于整个表。我可以对每个单独的单元格函数进行编码,但这不会产生非常干净的代码。

感谢您的宝贵时间!

excel vba loops countif
1个回答
0
投票

Do Loop
替换
For Loop
可以简化逻辑并且不易崩溃。

    Dim r As Long
    For r = 3 To 7
        .Cells(r, 2).Value2 = WorksheetFunction.CountIfs(BD.Range("AF:AF"), _
            MD.Range("TC_Month").Cells(r, 1), BD.Range("R:R"), ">250", _
            BD.Range("AK:AK"), ">=" & (wk1), BD.Range("AK:AK"), _
            "<" & (wk2))
    Next

在公式中使用绝对和相对引用使我们能够一次将公式写入多个单元格。

Sub ConstData()
    Dim CurrentMonth As Date
    CurrentMonth = DateSerial(Year(Date), Month(Date), 1)
    
    With ThisWorkbook.Sheets("MonthData").Range("TC_Month")
        .Range("B2:F2").Value = Array(CurrentMonth, CurrentMonth + 7, CurrentMonth + 14, CurrentMonth + 21, CurrentMonth + 28)
        .Range("B3:E7").Formula = "=COUNTIFS(BuiltData!$AF:$AF, $A3, BuiltData!$R:$R, "">250"", BuiltData!$AK:$AK, "">=""&B$2, BuiltData!$AK:$AK, ""<""&C$2)"
        .Range("F3:F7").Formula = "=COUNTIFS(BuiltData!$AF:$AF, $A3, BuiltData!$R:$R, "">250"", BuiltData!$AK:$AK, "">=""&F$2)"
         .Value = .Value ' This line converts the formulas into values 
    End With
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.