Count columns based on date range

前提是你 提交于 2020-07-23 07:41:46

问题


I'm new to VBA. I'm trying to accomplish the below thing in VBA and not sure how to do this.

  1. In Column "K" in sheet "Latency" i have dates in the form of "11/10/2016 16:17". (there will be multiple dates in the column)
  2. In column "O" I have few vales in a cell "Pass" or Fail"

What I want to do is, when the script is run, it should first throw up a dialogue box asking the user to enter the date range. Once the user gives the date range, it should select that columns and look out for "Pass" in "o" column and count the value and update it in a particular cell.

I have tried the below code, but I'm not sure how to add the count value using the date range criteria:

Sub WBR()
Dim s As String
Dim r As Range
Dim wf As WorksheetFunction
Dim xlSheet As Worksheet
Set xlSheet = ActiveWorkbook.Worksheets("Latency") 'sets the worksheet
Set wf = Application.WorksheetFunction
Set r = xlSheet.Range("O:O")                       'sets the range to search
s = "Pass"
[AE4] = wf.CountIf(r, s)
s = "Fail"
[AE5] = wf.CountIf(r, s)

With ActiveWorkbook.Worksheets("TT")
    [AE119] = wf.CountIfs(.Range("G:G"), "Yes", _
                          .Range("K:K"), "Tablet")
 End With

With ActiveWorkbook.Worksheets("TT")                'no of tickets processed
    [AE119] = wf.CountIfs(.Range("G:G"), "Yes", _
                          .Range("I:I"), "<>Duplicate TT", _
                          .Range("K:K"), "Tablet")
End With

End Sub


回答1:


This is just a slight variation on your existing code:

Sub WBR()
    Dim wf As WorksheetFunction
    Set wf = Application.WorksheetFunction
    Dim MinDate As String
    Dim MaxDate As String
    MinDate = InputBox("Minimum Date")
    MaxDate = InputBox("Maximum Date")
    If Not (IsDate(MinDate) And IsDate(MaxDate)) Then
        MsgBox "You should have specified valid dates!"
        Exit Sub
    End If
    If CDate(MinDate) > CDate(MaxDate) Then
        MsgBox "You should have specified sensible dates!"
        Exit Sub
    End If

    With ActiveWorkbook.Worksheets("Latency")
        [AE4] = wf.CountIf(.Range("O:O"), "Pass")
        [AE5] = wf.CountIf(.Range("O:O"), "Fail")

        [AE6] = wf.CountIfs(.Range("K:K"), ">=" & CLng(CDate(MinDate)), _
                            .Range("K:K"), "<=" & Clng(CDate(MaxDate)), _
                            .Range("O:O"), "Pass")
    End With        
    With ActiveWorkbook.Worksheets("TT")
        [AE119] = wf.CountIfs(.Range("G:G"), "Yes", _
                              .Range("K:K"), "Tablet")
        'no of tickets processed
        [AE119] = wf.CountIfs(.Range("G:G"), "Yes", _
                              .Range("I:I"), "<>Duplicate TT", _
                              .Range("K:K"), "Tablet")
    End With
End Sub


来源:https://stackoverflow.com/questions/41421598/count-columns-based-on-date-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!