VBA in Excel - If 语句计数器不起作用

VBA in Excel - If statement Counter wont work

我一直在尝试让这个 VBA 脚本自动执行任务,但我无法让它工作。

基本上,我在 excel 中有一个包含多列和超过 1000 行的大任务列表。它包含任务、分配给谁以及它是打开还是关闭。

H 列是分配给谁,N 列是任务是打开还是关闭。

我正在尝试按姓氏搜索,如果它是开放的,可以在柜台添加一个。最终目标是统计一个人有多少未完成的任务。此外,N 列(任务状态)中的一些单元格有额外的文本,如评论等。我确信在单元格中搜索一个单词的 InStr 函数会更好,但我无法弄清楚......

这是我的代码

Sub statuscount()

Dim tasksheet As Worksheet
Dim simons_count As Integer

Set tasksheet = ThisWorkbook.Sheets("tasks")

lr = tasksheet.Cells(Rows.Count, 1).End(xlUp).Row

For x = 5 to lr
    If tasksheet.Cells(x, 8) = "Simons" And tasksheet.Cells(x, 14) = "OPEN" Then
       simons_count = simons_count + 1
End If

Next x

tasksheet.Range("$O").Value = simons_count

End Sub

感谢您的帮助!

在 VBA 中使用 If/And 变得棘手,你最好嵌套两个 if 语句:

For x = 5 to lr
    If tasksheet.Cells(x, 8) = "Simons" Then
        If InStr(tasksheet.Cells(x, 14).Value, "OPEN") > 0 Then
            simons_count = simons_count + 1
        End If
    End If
Next x

这是一个更通用的函数。插入一个模块并在其中传递以下代码。您可以像使用任何其他 Excel 内置函数

一样使用该函数
Function LastNamecounter(lastName As String, status As String) As Long
    LastNamecounter = 0
    Dim tasksheet As Worksheet
    Set tasksheet = ThisWorkbook.Sheets("tasks")
    lr = tasksheet.Cells(Rows.Count, 1).End(xlUp).Row

    For i = 5 To lr
        If InStr(tasksheet.Cells(i, 8).Value, lastName) <> 0 And InStr(tasksheet.Cells(i, 14).Value, status) <> 0 Then
           LastNamecounter = LastNamecounter + 1
        End If
    Next i
End Function