简体   繁体   中英

VBA If Countifs

I use the below to only instigate a certain piece of code if there is data,

If WorksheetFunction.CountIf(wksdata.Range("D:D"), "ASM001") > 0 Then

However, I need it to work under a CountIfs as well, as some sheets have more than one criteria, such as the example below where it uses BIR001, BIR004, BIR006, ITI001. I need it to continue if there is at least 1 of ANY of them.

If WorksheetFunction.CountIfs(wksdata.Range("D:D"), "BIR001", wksdata.Range("D:D"), "BIR004", wksdata.Range("D:D"), "BIR006", wksdata.Range("D:D"), "ITI001") > 0 Then

Can you help locate my error?

I realised I should be adding 4 CountIf functions together.

If (WorksheetFunction.CountIf(wksdata.Range("D:D"), "BIR001") _
    + WorksheetFunction.CountIf(wksdata.Range("D:D"), "BIR004") _
    + WorksheetFunction.CountIf(wksdata.Range("D:D"), "BIR006") _
    + WorksheetFunction.CountIf(wksdata.Range("D:D"), "ITI001")) > 0 Then

Looks a bit messy but does the job!

This would be a good way to make it less messy:

Dim count As Integer

With Application.WorksheetFunction
   count = .CountIf(wksdata.Range("D:D"), "BIR001") + _
           .CountIf(wksdata.Range("D:D"), "BIR004") + _
           .CountIf(wksdata.Range("D:D"), "BIR006") + _
           .CountIf(wksdata.Range("D:D"), "ITI001")
End With

If (count > 0) Then

这可能是使用一些方括号的机会,但是您不应该使用完整的列引用。

If CBool([SUMPRODUCT(--(D1:D99999={"BIR001","BIR004","BIR006","ITI001"}))]) Then

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM