I'm trying to figure out how to expand the code below with the following countif conditions:
- If a row in Workbbook 1(wbSource) has the values in Column H = "01.January" and Column AD = < 50 then count and enter the result in cell B8 in Sheet 2 of Workbook 2(ThisWorkbook) after the whole wbSource is checked.
- If a row in wbSource has the values Column H = "01.January" and Column AD = > 50 and < 100 then count and enter the result in cell B9 in Sheet 2 of ThisWorkbook after the whole wbSource is checked.
- If a row in wbSource has the values Column H = "01.January" and Column AD = > 100 then count and enter the result in cell B10 in Sheet 2 of ThisWorkbook after the whole wbSource is checked.
This should be repeated for every month.
The entire concept is based around an user form with a file explorer function, where the user can select an excel file and evaluate it automatically based on the avarage_calc and countif conditions by clicking on a command button. Thats why I would need it as VBA.
Any idea how to add the countif function based on the conditions above, as addition to my existing code?
Private Sub CommandButton2_Click() ' update averages
Const YEAR = 2019
' open source workbook
Dim fname As String, wbSource As Workbook, wsSource As Worksheet
fname = Me.TextBox1.Text
If Len(fname) = 0 Then
MsgBox "No file selected", vbCritical, "Error"
Exit Sub
End If
Set wbSource = Workbooks.Open(fname, False, True) ' no link update, read only
Set wsSource = wbSource.Sheets("Sheet1") ' change to suit
Dim wb As Workbook, ws As Worksheet
Set wb = ThisWorkbook
Set ws = wb.Sheets("Table 2") '
' scan down source workbook calc average
Dim iRow As Long, lastRow As Long
Dim sMth As String, iMth As Long
Dim count(12) As Long, sum(12) As Long
lastRow = wsSource.Cells(Rows.count, 1).End(xlUp).Row
For iRow = 1 To lastRow
If IsDate(wsSource.Cells(iRow, 8)) _
And IsNumeric(wsSource.Cells(iRow, 30)) Then
iMth = Month(wsSource.Cells(iRow, 8)) ' col H
sum(iMth) = sum(iMth) + wsSource.Cells(iRow, 30) ' Col AD
count(iMth) = count(iMth) + 1 '
End If
Next
' close source worbook no save
wbSource.Close False
' update Table 2 with averages
With ws.Range("A3")
For iMth = 1 To 12
.Offset(0, iMth - 1) = MonthName(iMth) & " " & YEAR
If count(iMth) > 0 Then
.Offset(1, iMth - 1) = sum(iMth) / count(iMth)
.Offset(1, iMth - 1).NumberFormat = "0.0"
End If
Next
End With
Dim msg As String
msg = iRow - 1 & " rows scanned in " & TextBox1.Text
MsgBox msg, vbInformation, "Table 2 updated"
End Sub