计算具有特定文本的行数

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

我有一项任务来计算包含特定文本的行数并在电子邮件中打印该值。

Public Function First()
    Dim Source As Workbook
    Dim Var1 As Integer
    Dim Var10 As Integer
    Dim Source2 As Workbook

    Set Source = Workbooks.Open("C:\Users\HP\Desktop\IN INPROG.xlsx")

    Var1 = Application.WorksheetFunction.CountIf(Range("M1:M100"), "Orange")

    Source.Close SaveChanges:=False

    Set Source2 = Workbooks.Open("C:\Users\HP\Desktop\SR INPROG.xlsx")

    Var10 = Application.WorksheetFunction.CountIf(Range("M1:M100"), "Orange")

    Source2.Close SaveChanges:=False

    eTo = "[email protected]"
    esubject = Format(Date, "d/mmmm/yyyy") & " " & "Weekly Open Incident Reminder"
    ebody = "Dear All," & vbCrLf & "" & vbCrLf & "" & vbCrLf & "Orange: " & "SR: " & Var10 & " IN: " & Var1 

    Set app = CreateObject("Outlook.Application")
    Set itm = app.createitem(0)
    On Error Resume Next
    With itm
        .Subject = esubject
        .To = eTo
        .body = ebody
        .display

我的代码将所有值都返回为“0”,即使其中一行中存在“橙色”。

excel-vba rows vba excel
3个回答
0
投票

如果需要计算字符串中包含单词的任何行,可以将countif函数中的字符串从“Orange”修改为"*Orange*"

*通配符表示任意数量的字符。例如。字符串“Three orange balloons”的单元格将不计算在内

CountIf(Range("M1:M100"), "Orange")但将由CountIf(Range("M1:M100"), "*Orange*")


0
投票

感谢您的解决方案,我已经找到了我的问题的答案,我将在此处发布

Set Source = Workbooks.Open("C:\Users\itsm-student\Downloads\IN INPROG.xlsx")
Set Wks = Source.Worksheets("IN INPROG")

Var1 = Application.WorksheetFunction.CountIf(Wks.Range("M1:M100"), "*Orange*")

我需要做的是基本上为你要引用的工作表设置一个变量,在我的例子中它将是“IN PROG”并在声明范围时调用变量。我在顶部发布的代码是正确的,但是不是在源excel表中查看文本“orange”,而是在excel文件上找到我执行VBA的文本值。希望能帮助到你


0
投票

我做了:

Sub Worksheet_Change(ByVal Target As Range)

Set Source = ThisWorkbook

Dim Var1 As Integer

Set Wks = Source.Worksheets("Recebimento")

Var1 = Application.WorksheetFunction.CountIf(Wks.Range("U:U"), "*NOK*")

If Var1 > 0 Then
 'your code

End sub
© www.soinside.com 2019 - 2024. All rights reserved.