samedi 29 août 2015

Using VBA to assign a criterion for average.ifs()

I use the following formula in excel

=AVERAGEIFS(B4:B440;A4:A440;"<"&A441;A4:A440;">"&EDATE(A441;-6))

to get the average of a range of values, based on the values in an adjacent column. However I need to apply this formula for more than a thousand dates (column A contains dates). I have a macro, which asks the user to specify sheet name and date (using dialog boxes). So I would like to add some code, that takes the date specified by the user and replaces cell A441 from the above formula with it. Then copy the average, so that I can paste it where desired. Here is what I tried coding so far, with no success:

Sub Find()

Dim FindString As Date
Dim Sumact As Range
Dim Analyst As Double
Dim shname As String
        Do Until WorksheetExists(shname)
                      shname = InputBox("Enter sheet name")
                      If Not WorksheetExists(shname) Then MsgBox shname & " doesn't exist!", vbExclamation
                Loop
                Sheets(shname).Select
FindString = InputBox("Enter a Search value")
If Trim(FindString) <> "" Then
    With Sheets(shname).Range("A:A")
        Set Sumact = .Find(What:=FindString, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Sumact Is Nothing Then
            Application.Goto Sumact, True
        Else
            MsgBox "Nothing found"
        End If
    End With
End If   
 Set Analyst = Application.AverageIf(Range(("B:B"), ("A:A")), "<Sumact")
Selection.Copy 
End Sub

Aucun commentaire:

Enregistrer un commentaire