' === Pratica Obrigatoria 1 (ATIVO) ===
Option Explicit

Sub ConsultarEstoqueComFiltroCategoria()
    Dim cnn As Object, rs As Object
    Dim ws As Worksheet
    Dim strBanco As String, strSQL As String
    Dim strFiltroCat As String
    Dim i As Long
    
    Set ws = ThisWorkbook.Worksheets(1)
    strBanco = ThisWorkbook.Path & "\SIG_FastLog_Dados.accdb"
    If Dir(strBanco) = "" Then strBanco = "C:\FastLog_Dados\SIG_FastLog_Dados.accdb"
    
    strFiltroCat = Trim(ws.Range("H1").Value)
    
    Set cnn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")
    
    On Error GoTo TratarErro
    cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strBanco & ";"
    
    strSQL = "SELECT CodigoPeca, NomePeca, Categoria, QtdEstoque, EstoqueMinimo, PrecoUnitario " & _
             "FROM Pecas " & _
             "WHERE QtdEstoque <= EstoqueMinimo "
             
    If strFiltroCat <> "" Then
        strSQL = strSQL & "AND Categoria = '" & Replace(strFiltroCat, "'", "''") & "' "
    End If
    
    strSQL = strSQL & "ORDER BY QtdEstoque ASC;"
    
    rs.Open strSQL, cnn, 1, 1
    
    ws.Range("A2:F1000").ClearContents
    
    For i = 0 To rs.Fields.Count - 1
        ws.Cells(1, i + 1).Value = UCase(rs.Fields(i).Name)
        ws.Cells(1, i + 1).Font.Bold = True
    Next i
    
    If Not rs.EOF Then
        ws.Range("A2").CopyFromRecordset rs
        ws.Columns("A:F").AutoFit
    End If
    
    rs.Close
    cnn.Close
    Set rs = Nothing
    Set cnn = Nothing
    Exit Sub

TratarErro:
    MsgBox "Falha de Conexão SQL: " & Err.Description, vbCritical, "Erro ADODB"
    If Not rs Is Nothing Then If rs.State = 1 Then rs.Close
    If Not cnn Is Nothing Then If cnn.State = 1 Then cnn.Close
End Sub

