No VBA utilizo WorksheetFunction.NetworkDays.INTL(StartDate, EndDate, 7) - 1) e uma tabela de feriados para criar uma coluna calculada dos dias úteis entre datas. Em seguida, utilizo a rotina abaixo para fazer contagem com alguns critérios:
Código: Selecionar todos
Sub ConteSesVBA_Excel()
Dim i As Long
Dim wsO As Worksheet: Set wsO = wsDados
Dim wsD As Worksheet: Set wsD = wsDestino
Dim wkf As WorksheetFunction
Dim Data_Inicial As Date
Dim Data_Final As Date
Dim ultLin As Long
Dim t As Single
t = VBA.Timer
Set wkf = Application.WorksheetFunction
ultLin = wsD.Cells(Rows.Count, "A").End(xlUp).Row
Data_Inicial = wsD.Range("C2")
Data_Final = wsD.Range("D2")
For i = 5 To ultLin
For j = 3 To 11
wsD.Cells(i, j).Value = wkf.CountIfs(wsO.Range("A2:A" & Rows.Count), wsD.Cells(i, 1), _
wsO.Range("B2:B" & Rows.Count), wsD.Cells(i, 2), _
wsO.Range("D2:D" & Rows.Count), wsD.Cells(4, j).Value, _
wsO.Range("C2:C" & Rows.Count), ">=" & Format(Data_Inicial, "YYYY/MM/DD"), _
wsO.Range("C2:C" & Rows.Count), "<=" & Format(Data_Final, "YYYY/MM/DD"))
Next j
Next i
Debug.Print VBA.Timer - t
End Sub
A dúvida é possível fazer todos esses cálculos em uma única rotina, porém utilizando instruções de SQL dentro do VBA?
É possível utilizar, por exemplo, DATEDIFF com uma tabela de feriados e excluindo também finais de semana (sábado e domingo):
Código: Selecionar todos
Sub Cacl_Dias_Uteis()
Dim sSQL As String
Dim dbCon As New ADODB.Connection
Dim RS As New ADODB.Recordset
With dbCon
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source= " & ThisWorkbook.FullName & ""
.Properties("Extended Properties") = "Excel 12.0 XML;HDR=YES"
.Open
End With
sSQL = "UPDATE [Vendas$] SET Data_Final = dateDiff('d', #2019/01/01#, #2019/12/31#) WHERE [Vendedor]='Vendedor_1'"
RS.Open sSQL, dbCon
End Sub