Option Strict Off
Option Explicit On


Imports fatd_faturamento.BLL.Repositorio
Imports fatd_faturamento.ENTIDADE
Imports CrystalDecisions.CrystalReports.Engine
Imports VB = Microsoft.VisualBasic
Public Class frmRelEFechamentoVw

    Inherits System.Windows.Forms.Form
    Private objAtualizaBancoDados As New entidadeAtualizaBancoDados
    Private repositorioAtualizaBancoDados As New repositorioAtualizaBancoDados

    Private objExecAtualizaBancoDados As New entidadeAtualizaBancoDados
    Private repositorioExecAtualizaBancoDados As New repositorioAtualizaBancoDados
    Private dt, dt_1, dt_2, dt_3, dtinterno As DataTable

    Private ExcelAPP As Microsoft.Office.Interop.Excel.Application
    Private ExcelPasta As Microsoft.Office.Interop.Excel.Workbook
    Private ExcelPlanilha As Microsoft.Office.Interop.Excel.Worksheet

    Private istrNmArq As String
    Private LinhaPlan As Long

    Dim iblnQuebra As Boolean
    Dim istrSocios As String
    Dim istrCidade As String
    Dim istrUF As String
    Dim istrGrupoG As String
    Dim istrTabNf As String
    Dim istrTabTemp As String
    Dim istrTabTempItens As String
    Dim ilngControleLinha As Integer
    Dim istrCabec As String
    Dim istrCabec_1 As String
    Dim istrCabec_2 As String
    Dim strCol(4, 60) As String
    Dim iblnTar_AL As Boolean
    Dim iblnTar_AV As Boolean
    Dim iblnTar_AA As Boolean
    Dim iblnTar_A4 As Boolean
    Dim iblnTar_AS As Boolean
    Dim iblnTar_AX As Boolean
    Dim iblnTar_B As Boolean
    Dim iblnTotalizado As Boolean
    Dim iblnAnual As Boolean
    Dim istrMesAnoFat As String
    Dim llngNconsFimAno As Integer
    Dim lstrTotGeral As String
    Dim lstrOficial As String
    Dim ds_Relatorio As DataSet
    Dim dt_Relatorio_1 As DataTable
    Dim dt_Relatorio_2 As DataTable

    Dim istrNomClass As Object


#Region "Propriedades"

    Private Sub frmRelEFechamento_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim lintIdx As Short
        Dim ldteBase As Date
        Dim lstrMes As String
        Dim lstrAux As String

        Try

            iblnTotalizado = False
            iblnAnual = False

            'sAnoMesFat = GetConfig("mes.ano.faturamento")
            'If sAnoMesFat = "" Then sAnoMesFat = Format(Date.Now, "MM/yyyy")

            istrMesAnoFat = GetConfig("mes.ano.faturamento")

            istrTabNf = "NF"

            'Periodo
            ldteBase = Date.Now
            lstrMes = VB6.Format(Month(ldteBase), "00")
            Me.txtAno.Text = CStr(Year(ldteBase))

            With Me.cmbMesIni
                For lintIdx = 0 To .Items.Count
                    If VB6.GetItemString(Me.cmbMesIni, lintIdx) = lstrMes Then
                        .SelectedIndex = lintIdx
                        lintIdx = .Items.Count
                    End If
                Next lintIdx
                Me.cmbMesFim.SelectedIndex = .SelectedIndex
            End With

            'Verifica se o cliente possue sistema de socios
            istrSocios = Trim(GetConfig("possue.sistema.socios"))
            If istrSocios = "-1" Then
                If gstrEmpresa_Sigla = "COORSEL" Or gstrEmpresa_Sigla = "CERGAL" Then
                    istrSocios = "1"
                Else
                    istrSocios = "0"
                End If
                SetConfig("possue.sistema.socios", "String", istrSocios, istrSocios, "Possuem sistema de sócios. 0 = Não, 1 = Sim.")
            ElseIf Len(istrSocios) = 0 Then
                If gstrEmpresa_Sigla = "COORSEL" Or gstrEmpresa_Sigla = "CERGAL" Then
                    istrSocios = "1"
                Else
                    istrSocios = "0"
                End If
                SetConfig("possue.sistema.socios", "String", istrSocios, istrSocios, "Possuem sistema de sócios. 0 = Não, 1 = Sim.")
            End If

            'Define o nome das tabelas para o relatorio
            istrTabTemp = "temp_estatis_" & VB6.Format(Date.Now, "yyyymmddHHMMSS")
            istrTabTempItens = istrTabTemp & "_itens"
            istrTabNf = IIf(Me.chkTrans.CheckState = System.Windows.Forms.CheckState.Checked, "NFTRANSICAO", "NF")


            'Divisão Residencial
            lintIdx = 0
            lstrAux = ""
            lstrAux = GetConfig("divisao.residencial")
            If lstrAux <> "" And lstrAux <> "-1" Then
                lintIdx = Len(lstrAux)
            End If
            If lintIdx <> 0 Then
                PegarFaixaRes(lstrAux, Me.MSFGridRes)
            End If

            'Divisão Baixa Renda
            lintIdx = 0
            lstrAux = ""
            lstrAux = GetConfig("divisao.baixa.renda")
            If lstrAux <> "" And lstrAux <> "-1" Then
                lintIdx = Len(lstrAux)
            End If
            If lintIdx <> 0 Then
                PegarFaixaRes(lstrAux, Me.MSFGridTarifa)
            End If


            Me.cmbModelo.SelectedIndex = 0
            Me.cmbSocios.SelectedIndex = 0
            Me.cmbTipo.SelectedIndex = 0

            If istrSocios = "0" Then Me.cmbSocios.Enabled = False

            PreencheCombobox()
            PreencherListView()

            Me.cmbRotaIni.SelectedIndex = 0

            If cmbRotaFim.Items.Count > 0 Then
                Me.cmbRotaFim.SelectedIndex = cmbRotaFim.Items.Count - 1
            Else
                Me.cmbRotaFim.SelectedIndex = 0
            End If

            txtArq.Enabled = False
            cmdPasta.Enabled = False

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: frmRelEFechamento_Load" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lsvDtLeit_Click(sender As Object, e As EventArgs) Handles lsvDtLeit.Click

        Try

            'If lsvDtLeit.Items.Count > 0 Then

            '    If lsvDtLeit.FocusedItem.[Text].ToString() = "Todas" Then

            '        If lsvDtLeit.FocusedItem.Checked = True Then
            '            CheckAllListView(lsvDtLeit, False)
            '        ElseIf lsvDtLeit.FocusedItem.Checked = False Then
            '            CheckAllListView(lsvDtLeit, True)
            '        End If

            '    Else
            '        If lsvDtLeit.FocusedItem.Checked = False Then
            '            lsvDtLeit.Items.Item(0).Checked = False
            '            lsvDtLeit.FocusedItem.Checked = True
            '        Else
            '            lsvDtLeit.Items.Item(0).Checked = False
            '            lsvDtLeit.FocusedItem.Checked = False
            '        End If

            '    End If

            'End If


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lsvDtLeit_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lvsCidades_Click(sender As Object, e As EventArgs) Handles lvsCidades.Click

        Try

            'If lvsCidades.Items.Count > 0 Then

            '    If lvsCidades.FocusedItem.[Text].ToString() = "Marcar Todas" Then

            '        If lvsCidades.FocusedItem.Checked = True Then
            '            CheckAllListView(lvsCidades, False)
            '        ElseIf lvsCidades.FocusedItem.Checked = False Then
            '            CheckAllListView(lvsCidades, True)
            '        End If

            '    Else
            '        If lvsCidades.FocusedItem.Checked = False Then
            '            lvsCidades.Items.Item(0).Checked = False
            '            lvsCidades.FocusedItem.Checked = True
            '        Else
            '            lvsCidades.Items.Item(0).Checked = False
            '            lvsCidades.FocusedItem.Checked = False
            '        End If

            '    End If

            'End If


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lvsCidades_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub chkOficial_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles chkOficial.CheckStateChanged

        Try


            If Me.chkOficial.CheckState = System.Windows.Forms.CheckState.Checked Then
                MessageBox.Show("Nenhuma fatura referente ao mês poderá mais ser recalculada.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If



        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: chkOficial_CheckStateChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub chkTrans_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles chkTrans.CheckStateChanged

        Try

            istrTabNf = IIf(Me.chkTrans.CheckState = 1, "NFTRANSICAO", "NF")


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: chkTrans_CheckStateChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmbMesFim_TextChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmbMesFim.TextChanged

        Try

            With Me.cmbMesFim
                If VB6.GetItemString(Me.cmbMesFim, .SelectedIndex) <> "" Then
                    If VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) <> "" Then
                        If VB6.GetItemString(Me.cmbMesIni, Me.cmbMesFim.SelectedIndex) > VB6.GetItemString(Me.cmbMesFim, .SelectedIndex) Then
                            Me.cmbMesIni.SelectedIndex = .SelectedIndex
                        End If
                    End If
                End If
            End With

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmbMesFim_TextChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmbMesFim_SelectedIndexChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmbMesFim.SelectedIndexChanged

        Try

            cmbMesFim_TextChanged(cmbMesFim, New System.EventArgs())

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmbMesFim_SelectedIndexChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmbMesIni_TextChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmbMesIni.TextChanged

        Try

            With Me.cmbMesIni
                If VB6.GetItemString(Me.cmbMesIni, .SelectedIndex) <> "" Then
                    If VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex) <> "" Then
                        If VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex) < VB6.GetItemString(Me.cmbMesIni, .SelectedIndex) Then
                            Me.cmbMesFim.SelectedIndex = .SelectedIndex
                        End If
                    End If
                End If
            End With

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmbMesIni_TextChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmbMesIni_SelectedIndexChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmbMesIni.SelectedIndexChanged

        Try

            cmbMesIni_TextChanged(cmbMesIni, New System.EventArgs())

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmbMesIni_SelectedIndexChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmbRotaFim_TextChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmbRotaFim.TextChanged

        Try

            With Me.cmbRotaFim
                If VB6.GetItemString(Me.cmbRotaFim, .SelectedIndex) <> "" Then
                    If VB6.GetItemString(Me.cmbRotaIni, Me.cmbRotaIni.SelectedIndex) <> "" Then
                        If VB6.GetItemString(Me.cmbRotaIni, Me.cmbRotaIni.SelectedIndex) > VB6.GetItemString(Me.cmbRotaFim, .SelectedIndex) Then
                            Me.cmbRotaIni.SelectedIndex = .SelectedIndex
                        End If
                    End If
                End If
            End With

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmbRotaFim_TextChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmbRotaFim_SelectedIndexChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmbRotaFim.SelectedIndexChanged

        Try

            cmbRotaFim_TextChanged(cmbRotaFim, New System.EventArgs())

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmbRotaFim_SelectedIndexChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmbRotaIni_TextChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmbRotaIni.TextChanged

        Try

            With Me.cmbRotaIni
                If VB6.GetItemString(Me.cmbRotaIni, .SelectedIndex) <> "" Then
                    If VB6.GetItemString(Me.cmbRotaFim, Me.cmbRotaFim.SelectedIndex) <> "" Then
                        If VB6.GetItemString(Me.cmbRotaFim, Me.cmbMesFim.SelectedIndex) < VB6.GetItemString(Me.cmbRotaIni, .SelectedIndex) Then
                            Me.cmbRotaFim.SelectedIndex = .SelectedIndex
                        End If
                    End If
                End If
            End With

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmbRotaIni_TextChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmbRotaIni_SelectedIndexChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmbRotaIni.SelectedIndexChanged

        Try

            cmbRotaIni_TextChanged(cmbRotaIni, New System.EventArgs())

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmbRotaIni_SelectedIndexChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub txtAno_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles txtAno.Enter

        Try

            With Me.txtAno
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
            End With

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: txtAno_Enter" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub txtAno_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles txtAno.KeyPress

        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)

        Try


            If KeyAscii = System.Windows.Forms.Keys.Return Then
                TabEnter(KeyAscii, eventArgs)
            ElseIf KeyAscii <> System.Windows.Forms.Keys.Back And (KeyAscii < System.Windows.Forms.Keys.D0 Or KeyAscii > System.Windows.Forms.Keys.D9) Then
                KeyAscii = 0
            End If

            eventArgs.KeyChar = Chr(KeyAscii)

            If KeyAscii = 0 Then
                eventArgs.Handled = True
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: txtAno_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Sub cmdPasta_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdPasta.Click

        Try
            If chkPlanilha.Checked = True Then

                Dim lstrAux As String
                Try
                    Call NomeArquivo()
                    fbdTsee.ShowDialog()
                    lstrAux = fbdTsee.SelectedPath & "\"
                    ''Me.txtArquivo.Text = StrReverse(Mid(lstrAux, CInt(InStr(lstrAux, "\")))) & istrNmArq & ".XLS" '& IIf(Me.chkPlanilha.Checked, "XML", "XLS")
                    Me.txtArq.Text = lstrAux & istrNmArq & ".XLS" '& IIf(Me.chkPlanilha.Checked, "XML", "XLS")
                Catch ex As Exception
                    MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdArquivo_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Exit Sub
                End Try

            Else


                Dim lstrAux As String
                Dim lstrArq As String

                lstrArq = "RelFec_" & Replace(Me.txtAno.Text & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) & "_" & VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex), "/", "")

                With Me.dialArqOpen
                    .DefaultExt = "CSV"
                    .Filter = .DefaultExt & "(*." & .DefaultExt & ")" & "|*." & .DefaultExt
                    If Trim(Me.txtArq.Text) <> "" Then
                        .FileName = StrReverse(Mid(StrReverse(Me.txtArq.Text), CInt(InStr(StrReverse(Me.txtArq.Text), "\")))) & lstrArq & "." & .DefaultExt
                    Else
                        .FileName = My.Application.Info.DirectoryPath & "\" & lstrArq & "." & .DefaultExt
                    End If
                    .Title = "Arquivo de exportação dos dados de faturamento"
                    .ShowDialog()
                    lstrAux = StrReverse(.FileName)
                    Me.txtArq.Text = StrReverse(Mid(lstrAux, CInt(InStr(lstrAux, "\")))) & lstrArq & "." & .DefaultExt
                End With

            End If
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdPasta_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmdFechar_Click(sender As Object, e As EventArgs) Handles cmdFechar.Click
        Try

            lClose()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdFechar_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Sub cmdImprimir_Click(sender As Object, e As EventArgs) Handles cmdImprimir.Click

        Try

            lPrint()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdImprimir_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmdExporta_Click(sender As Object, e As EventArgs) Handles cmdExporta.Click

        Try

            If Me.txtArq.Text <> "" Then
                If istrTabTemp = "" Then
                    istrTabTemp = "temp_estatis_" & VB6.Format(Date.Now, "yyyymmddHHMMSS")
                End If
                lExportarCSV()
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdExporta_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub cmdCarregaLeitura_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCarregaLeitura.Click

        Dim lstrTabela As String

        Try

            If Me.chkTrans.CheckState = System.Windows.Forms.CheckState.Checked And Me.chkPreviaFat.CheckState = System.Windows.Forms.CheckState.Checked Then
                lstrTabela = "NF"
            ElseIf Me.chkTrans.CheckState = System.Windows.Forms.CheckState.Checked Then
                lstrTabela = "NFTRANSICAO"
            Else
                lstrTabela = "NF"
            End If

            PreencherListViewDataLeitura(lsvDtLeit, lstrTabela)

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: cmdCarregaLeitura_Click" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub FrmRelEFechamento_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress

        Dim KeyAscii As Short = Asc(eventArgs.KeyChar)

        Try

            If KeyAscii = System.Windows.Forms.Keys.Escape Then
                cmdFechar_Click(cmdFechar, New System.EventArgs())
            ElseIf KeyAscii = System.Windows.Forms.Keys.Return Then
                TabEnter(KeyAscii, eventArgs)
            End If

            eventArgs.KeyChar = Chr(KeyAscii)

            If KeyAscii = 0 Then
                eventArgs.Handled = True
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: FrmRelEFechamento_KeyPress" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub FrmRelEFechamento_FormClosed(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed

        Dim objTempEstatisItens As New entidadeTempEstatisItens
        Dim repositorioTempEstatisItens As New repositorioTempEstatisItens

        Dim objTempEstatis As New entidadeTempEstatis
        Dim repositorioTempEstatis As New repositorioTempEstatis

        Try

            'Dropa a tabela caso exista
            objTempEstatis.TABLE = istrTabTemp
            objTempEstatisItens.TABLE = istrTabTempItens

            repositorioTempEstatis.Execute_1(objTempEstatis)
            repositorioTempEstatisItens.Execute_1(objTempEstatisItens)


            If iblnTotalizado Then
                frmPrincipal.mnuRelatorio_ConferenciaFaturamento.Enabled = True
            ElseIf iblnAnual Then
                frmPrincipal.mnuRelatorio_Fechamento_TotalFaturamentoAnual.Enabled = True
            End If


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: FrmRelEFechamento_FormClosed" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

#End Region

#Region "Métodos"

    Private Sub lClose()

        Try

            Close()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lClose" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub CheckAllListView(ByRef vlist As System.Windows.Forms.ListView, ByVal vCheck As Boolean)

        Dim i As Integer

        Try
            For i = 0 To vlist.Items.Count - 1
                vlist.Items.Item(i).Checked = vCheck
            Next i
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: CheckAllListView" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lPrint()

        Dim lstrCid As String
        Dim lstrZon As String
        Dim lintAux As Short
        Dim lblnAux As Boolean
        Dim lstrFil As String
        Dim ldblAnomes As Double

        Dim objRelatorioOficializado As New entidadeRelatorioOficializado
        Dim repositorioRelatorioOficializado As New repositorioRelatorioOficializado

        Dim objTempEstatisItens As New entidadeTempEstatisItens
        Dim repositorioTempEstatisItens As New repositorioTempEstatisItens

        Dim objTempEstatis As New entidadeTempEstatis
        Dim repositorioTempEstatis As New repositorioTempEstatis

        Dim rpt As New ReportDocument()

        Try

            lstrOficial = ""

            ldblAnomes = CDbl(Me.txtAno.Text & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex))

            ' If VerificaExisteRegistro("relatorio_oficializado", "anomes = " & ldblAnomes & "") Then
            If VerificaExisteRegistroRet("relatorio_oficializado", "anomes = " & ldblAnomes & "") Then
                lstrOficial = "S"
            End If

            If Me.chkOficial.CheckState = System.Windows.Forms.CheckState.Checked Then

                If lstrOficial <> "S" Then

                    objRelatorioOficializado.ANOMES = ldblAnomes

                    repositorioRelatorioOficializado.Insert(objRelatorioOficializado)

                    lstrOficial = "S"

                End If

            End If

            lblnAux = True


            If Not iblnTotalizado Then

                If Not iblnAnual Then
                    'Arlindo 30/08/23
                    'If (istrMesAnoFat = (VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) & "/" & Me.txtAno.Text)) Or (istrMesAnoFat = (VB6.GetItemString(Me.cmbMesIni, Me.cmbMesFim.SelectedIndex) & "/" & Me.txtAno.Text)) Then
                    '    lblnAux = False
                    'End If
                End If

            End If

            If lblnAux Then

                ilngControleLinha = 769

                ' ----- Verifica se foi selecionada alguma cidade
                lblnAux = False
                lstrZon = ""
                lstrFil = ""

                With Me.lvsCidades

                    For lintAux = 0 To .Items.Count - 1
                        If .Items.Item(lintAux).Checked = True Then
                            lblnAux = True
                            lstrFil = lstrFil & "'" & .Items.Item(lintAux).SubItems(1).Text & "',"
                        End If
                    Next lintAux

                    If Trim(lstrFil) <> "" Then
                        lstrFil = Microsoft.VisualBasic.Left(lstrFil, Len(lstrFil) - 1)
                    End If

                End With

                If Not lblnAux Then
                    MessageBox.Show("Você deve ao menos selecionar uma cidade na lista", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Else

                    Me.Cursor = System.Windows.Forms.Cursors.WaitCursor

                    LigDesObj(False)

                    Me.lblInfo.Text = " Montando dados para exibição..."
                    Me.lblInfo.Refresh()

                    '----------------------------------------------
                    'Dropa a tabela caso exista
                    objTempEstatis.TABLE = istrTabTemp
                    objTempEstatisItens.TABLE = istrTabTempItens

                    repositorioTempEstatis.Execute_1(objTempEstatis)
                    repositorioTempEstatisItens.Execute_1(objTempEstatisItens)

                    '----------------------------------------------

                    If MontaTabela(lstrFil) Then

                        Me.lblInfo.Text = " Montando Relatório..."
                        Me.lblInfo.Refresh()

                        ds_Relatorio = New DataSet()

                        dt_Relatorio_1 = New DataTable()
                        dt_Relatorio_1.Columns.Add("GRUPO101", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO102", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO103", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO104", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO105", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO106", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO107", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO108", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO109", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO110", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO111", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO112", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO113", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO114", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO115", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO116", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO117", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO118", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO119", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO120", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO121", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO122", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO123", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO124", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO125", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO126", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO127", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO128", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO129", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO130", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO131", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO132", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO133", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO134", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO135", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO136", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO137", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO138", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO139", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO140", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO141", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO142", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO143", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO144", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO145", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO146", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO147", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO148", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO149", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO150", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO151", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO152", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO153", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO154", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO155", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO156", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO157", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO158", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO159", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO160", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO201", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO202", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO203", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO204", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO205", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO206", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO207", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO208", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO209", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO210", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO211", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO212", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO213", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO214", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO215", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO216", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO217", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO218", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO219", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO220", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO221", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO222", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO223", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO224", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO225", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO226", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO227", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO228", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO229", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO230", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO231", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO232", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO233", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO234", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO235", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO236", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO237", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO238", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO239", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO240", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO241", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO242", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO243", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO244", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO245", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO246", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO247", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO248", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO249", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO250", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO251", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO252", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO253", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO254", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO255", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO256", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO257", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO258", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO301", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO302", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO303", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO304", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO305", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO306", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO307", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO308", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO309", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO310", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO311", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO312", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO313", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO314", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO315", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO316", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO317", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO318", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO319", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO320", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO321", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO322", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO323", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO324", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO325", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO326", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO327", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO328", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO329", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO330", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO331", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO332", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO333", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO334", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO335", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO336", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO337", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO338", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO401", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO402", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO403", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO404", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO405", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO406", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO407", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO408", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO409", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO410", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO411", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO412", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO413", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO414", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO415", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO416", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO417", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO418", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO419", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO420", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO421", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO422", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO423", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO424", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO425", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO426", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO427", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO428", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO429", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO430", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO431", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO432", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO433", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO434", GetType(String))
                        dt_Relatorio_1.Columns.Add("CABECALHO01", GetType(String))
                        dt_Relatorio_1.Columns.Add("CABECALHO02", GetType(String))
                        dt_Relatorio_1.Columns.Add("GRUPO", GetType(String))
                        dt_Relatorio_1.Columns.Add("TIPO", GetType(String))
                        dt_Relatorio_1.Columns.Add("NOMEEMPRESA", GetType(String))
                        dt_Relatorio_1.Columns.Add("ENDERECOEMPRESA", GetType(String))
                        dt_Relatorio_1.Columns.Add("FONESITEEMPRESA", GetType(String))
                        dt_Relatorio_1.Columns.Add("IMAGE", GetType(Byte()))

                        dt_Relatorio_2 = New DataTable()
                        dt_Relatorio_2.Columns.Add("TIPO", GetType(String))
                        dt_Relatorio_2.Columns.Add("CODIGO", GetType(String))
                        dt_Relatorio_2.Columns.Add("DESCRICAO", GetType(String))
                        dt_Relatorio_2.Columns.Add("VALOR", GetType(String))
                        dt_Relatorio_2.Columns.Add("TOTAL", GetType(String))
                        dt_Relatorio_2.Columns.Add("CABECALHO01", GetType(String))
                        dt_Relatorio_2.Columns.Add("CABECALHO02", GetType(String))


                        If chkPlanilha.Checked = True Then
                            Dim misValue As Object = System.Reflection.Missing.Value
                            ExcelAPP = New Microsoft.Office.Interop.Excel.Application
                            ExcelPasta = ExcelAPP.Workbooks.Add(misValue)
                            ExcelPlanilha = ExcelPasta.Worksheets.Add()
                            ExcelPlanilha.Name = "Plan1"
                            ExcelPlanilha.Activate()

                            Me.lblInfo.Text = " Montando Planilha"
                            Me.lblInfo.Refresh()

                            If txtArq.Text = "" Then
                                MessageBox.Show("Planilha gerada com sucesso !", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information)
                            End If

                            sGeraPlan()

                            ExcelPlanilha.SaveAs(txtArq.Text)
                            ExcelPasta.Close()
                            ExcelAPP.Quit()

                            MessageBox.Show("Planilha gerada com sucesso !", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information)

                        Else


                            istrCabec = " Total por Classe"

                        'Grupo A
                        Me.lblInfo.Text = " Montando Relatório (Grupo A)"
                        Me.lblInfo.Refresh()

                        If chkGrupoA.Checked And chkGrupoB.Checked Then

                            CabecaRel("(AB)" & istrCabec)
                            RelEstat_Operacional("AB", "", istrCabec_1, istrCabec_2)
                            ImprimeDetalhes("AB", "", istrCabec_1, istrCabec_2)

                        ElseIf chkGrupoA.Checked Then

                            CabecaRel("(A)" & istrCabec)
                            RelEstat_Operacional("A", "", istrCabec_1, istrCabec_2)
                            ImprimeDetalhes("A", "", istrCabec_1, istrCabec_2)

                        ElseIf chkGrupoB.Checked Then

                            CabecaRel("(B)" & istrCabec)
                            RelEstat_Operacional("B", "", istrCabec_1, istrCabec_2)
                            ImprimeDetalhes("B", "", istrCabec_1, istrCabec_2)

                        End If


                        Me.lblInfo.Text = " Pronto!"
                        Me.lblInfo.Refresh()

                        ds_Relatorio.Tables.Add(dt_Relatorio_1)
                        ds_Relatorio.Tables(0).TableName = "REL_FECHAMENTO_FATURAMENTO_1"

                        ds_Relatorio.Tables.Add(dt_Relatorio_2)
                        ds_Relatorio.Tables(1).TableName = "REL_FECHAMENTO_FATURAMENTO_2"


                        If ds_Relatorio.Tables(0).Rows.Count = 0 Then
                            MessageBox.Show("Não há registros para o relatório escolhido! ", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                            Exit Sub
                        Else

                            rpt = New rptFechamentoFaturamento

                            rpt.SetDataSource(ds_Relatorio)

                            frmViewRelatorios.rpt = rpt

                            frmViewRelatorios.CRViewer.Zoom((100))
                            frmViewRelatorios.Text = "Relatório de Fechamento de Faturamento"
                            frmViewRelatorios.ShowDialog()

                        End If
                    End If
                    Else
                            Me.lblInfo.Text = ""
                        Me.lblInfo.Refresh()
                    End If

                End If

                LigDesObj(True)
                Me.Cursor = System.Windows.Forms.Cursors.Default

            Else
                MessageBox.Show("Você não pode imprimir este relatório, pois o mês de faturamento " & istrMesAnoFat & " ainda não foi finalizado.", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lPrint" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Function lInsertFatura(ByRef objFatura As entidadeFatura) As Boolean
        Dim repositorioFatura As New repositorioFatura
        Try

            repositorioFatura.Insert(objFatura)

            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Private Function lInsertFaturaItens(ByRef objFaturaItens As entidadeFaturaItens) As Boolean
        Dim repositorioFaturaItens As New repositorioFaturaItens
        Try

            repositorioFaturaItens.Insert(objFaturaItens)

            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Private Sub PreencheCombobox()

        Try

            PreencherRotasNF(cmbRotaIni, "Ini")
            PreencherRotasNF(cmbRotaFim, "Fim")

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: PreencheCombobox" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub PreencherListView()

        Try

            'PreencherBaixaRenda(cmbFaixaBaixaRenda)
            'PreencherFaixaRes(cmbFaixaRes)
            PreencherListViewCidade(lvsCidades)
            PreencherListViewRotasPrefixo(lsvRotas)

            Dim pTabela As String = IIf(chkTrans.Checked = False And chkPreviaFat.Checked = False, "NF", "NFTRANSICAO")
            PreencherListViewDataLeitura(lsvDtLeit, pTabela)

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: PreencherListView" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub lExportarCSV()

        Dim lstrGrupo(8) As String
        Dim lstrQuebPri(8) As String
        Dim lstrClasse(14, 2) As String
        Dim lstrQuebSeg(14) As String
        Dim lintGruAux As Short
        Dim lintGrupo As Short
        Dim lintClass As Short
        Dim lstrLin As String
        Dim lstrArq As String
        Dim lintARQ As Short
        Dim lstrSql As String
        Dim lstrWhe As String
        Dim lstrOrd As String

        Dim vlist

        Dim objTempEstatisItens As New entidadeTempEstatisItens
        Dim repositorioTempEstatisItens As New repositorioTempEstatisItens

        Dim objTempEstatis As New entidadeTempEstatis
        Dim repositorioTempEstatis As New repositorioTempEstatis

        Try


            lstrGrupo(0) = "A4"
            lstrGrupo(1) = "AV"
            lstrGrupo(2) = "AA"
            lstrGrupo(3) = "AL"
            lstrGrupo(4) = "ALS"
            lstrGrupo(5) = "ALP"
            lstrGrupo(6) = "AS"
            lstrGrupo(7) = "AX"
            lstrGrupo(8) = "B"

            lstrQuebPri(0) = "Grupo A - Convencional"
            lstrQuebPri(1) = "Grupo A - Verde"
            lstrQuebPri(2) = "Grupo A - Azul"
            lstrQuebPri(3) = "Grupo A - Livre"
            lstrQuebPri(4) = "Grupo A - Livre Especial"
            lstrQuebPri(5) = "Grupo A - Livre Parcialmente Cativo"
            lstrQuebPri(6) = "Grupo A - Suprimento"
            lstrQuebPri(7) = "Grupo A - Horo-sazonal Suprimento"
            lstrQuebPri(8) = "Grupo B "

            lstrClasse(1, 2) = "CLASSE = '9104'"
            lstrClasse(2, 2) = "CLASSE = '9105'"
            lstrClasse(3, 2) = "CLASSE = '9106'"
            lstrClasse(4, 2) = "CLASSE = '9101'"
            lstrClasse(5, 1) = "CLASSE BETWEEN 0000 AND 3999"
            lstrClasse(6, 1) = "CLASSE BETWEEN 4000 AND 4999"
            lstrClasse(7, 1) = "CLASSE BETWEEN 5000 AND 5999"
            lstrClasse(8, 1) = "CLASSE BETWEEN 6100 AND 6199"
            lstrClasse(9, 1) = "CLASSE BETWEEN 6200 AND 6299"
            lstrClasse(10, 1) = "CLASSE BETWEEN 6300 AND 6399"
            lstrClasse(11, 1) = "CLASSE BETWEEN 6400 AND 6499"
            lstrClasse(12, 2) = "CLASSE BETWEEN 7200 AND 7299"
            lstrClasse(13, 1) = "CLASSE BETWEEN 7100 AND 7199 AND CLASSE BETWEEN 7300 AND 7999 "
            lstrClasse(14, 2) = "CLASSE BETWEEN 8000 AND 8999"

            lstrQuebSeg(1) = "Residencial Baixa Renda (246)"
            lstrQuebSeg(2) = "Residencial Baixa Renda (485)"
            lstrQuebSeg(3) = "Residencial Baixa Renda (694)"
            lstrQuebSeg(4) = "Residencial Normal"
            lstrQuebSeg(5) = "Industrial"
            lstrQuebSeg(6) = "Comercial"
            lstrQuebSeg(7) = "Rural"
            lstrQuebSeg(8) = "Poder Público Municipal"
            lstrQuebSeg(9) = "Poder Público Estadual"
            lstrQuebSeg(10) = "Poder Público Federal"
            lstrQuebSeg(11) = "Iluminação Pública"
            lstrQuebSeg(12) = "Água, Esgosto e Saneamento"
            lstrQuebSeg(13) = "Serviço Público"
            lstrQuebSeg(14) = "Consumo Próprio"

            lstrLin = ""
            'lstrLin = lstrLin & "Classe;Número de Consumidores;"
            lstrLin = lstrLin & "Grupo;Classe;Zona;Livro;Conta;Nome;"
            lstrLin = lstrLin & "R$ Consumo Reativo Ponta;R$ Consumo Reativo Fora Ponta;"
            lstrLin = lstrLin & "R$ Demanda Reativa Ponta;R$ Demanda Reativa Fora Ponta;"
            lstrLin = lstrLin & "kWh Lido;kWh Faturado;R$ kWh Faturado;"
            lstrLin = lstrLin & "kWh Faturado. Ponta;R$ kWh Faturado Ponta;kWh Faturado Fora Ponta;R$ kWh Faturado Fora Ponta;"
            lstrLin = lstrLin & "kWh Devolvido Ponta;R$ kWh Devolvido Ponta;kWh Devolvido Fora Ponta;R$ kWh Devolvido Fora Ponta;"
            lstrLin = lstrLin & "kWh Ultrapassado Ponta;R$ kWh Ultrapassado Ponta;kWh Ultrapassado Fora Ponta;R$ kWh Ultrapassado Fora Ponta;"

            lstrLin = lstrLin & "kW Faturado;R$ kW Faturado;"
            lstrLin = lstrLin & "kW Faturado. Ponta;R$ kW Faturado Ponta;kW Faturado Fora Ponta;R$ kW Faturado Fora Ponta;"
            lstrLin = lstrLin & "kW Ultrapassado Ponta;R$ kW Ultrapassado Ponta;kW Ultrapassado Fora Ponta;R$ kW Ultrapassado Fora Ponta;"

            lstrLin = lstrLin & "R$ Desconto Provisório;R$ Desconto Realizado;R$ Devolução Diferença CCEE;R$ Cobrança Diferença CCEE;"

            lstrLin = lstrLin & "R$ Convênios;R$ Diversos;R$ Taxados;R$ Devolução;R$ Encargos Financeiros;R$ Retenção Federal;R$ CIP;R$ Juros ECE;R$ Diferença Eletrobrás;R$ Encargos;R$ Must;"
            lstrLin = lstrLin & "R$ Icms;R$ Pis;R$ Cofins;R$ Recebimentos Empresa;R$ Importe;R$ Total;Demanda Contratada Convencional;Demanda Contratada Ponta;Demanda Contratada Fora Ponta;"

            lintARQ = FreeFile()
            FileOpen(lintARQ, Me.txtArq.Text, OpenMode.Output)
            PrintLine(lintARQ, lstrLin)

            'Grupo A
            BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 0, 14, " Grupo A ")

            For lintClass = 1 To 14

                If lstrClasse(lintClass, 1) <> "" Then

                    For lintGrupo = 0 To 8

                        objTempEstatis.TABLE = istrTabTemp
                        objTempEstatis.GRUPO = lstrGrupo(lintGrupo)
                        objTempEstatis.CLASSE = lstrClasse(lintClass, 1)

                        vlist = repositorioTempEstatis.Select(objTempEstatis)

                        If vlist.Count > 0 Then

                            For Each objTempEstatisFor As entidadeTempEstatis In vlist

                                'If IIf(IsNull(objTempEstatisFor.qtd_consumidores), 0, objTempEstatisFor.qtd_consumidores) > 0 Then
                                lstrLin = lstrQuebPri(lintGrupo) & ";" & lstrQuebSeg(lintClass) & ";"
                                lstrLin = lstrLin & MontaLinhasCsv(objTempEstatisFor)
                                PrintLine(lintARQ, lstrLin)
                                'End If

                            Next

                        End If

                    Next lintGrupo

                End If

                BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 1,  , " Grupo A ")

            Next lintClass

            'Grupo B
            BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 0, 14, " Grupo B ")

            For lintClass = 1 To 14

                If lstrClasse(lintClass, 1) <> "" Then
                    lintGruAux = 1
                ElseIf lstrClasse(lintClass, 2) <> "" Then
                    lintGruAux = 2
                End If

                For lintGrupo = 0 To 8


                    objTempEstatis.TABLE = istrTabTemp
                    objTempEstatis.GRUPO = lstrGrupo(lintGrupo)
                    objTempEstatis.CLASSE = lstrClasse(lintClass, lintGruAux)

                    vlist = repositorioTempEstatis.Select(objTempEstatis)

                    If vlist.Count > 0 Then

                        For Each objTempEstatisFor As entidadeTempEstatis In vlist

                            'If IIf(IsNull(objTempEstatisFor.qtd_consumidores), 0, objTempEstatisFor.qtd_consumidores) > 0 Then
                            lstrLin = lstrQuebPri(lintGrupo) & ";" & lstrQuebSeg(lintClass) & ";"
                            lstrLin = lstrLin & MontaLinhasCsv(objTempEstatisFor)
                            PrintLine(lintARQ, lstrLin)
                            'End If

                        Next

                    End If

                Next lintGrupo

                BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 1,  , " Grupo B ")

            Next lintClass

            FileClose(lintARQ)

            MessageBox.Show("Arquivo gerado com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: lExportarCSV" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Public Sub PreencherListViewDataLeitura(ByRef vLista As System.Windows.Forms.ListView, ByRef pTabela As String)

        Dim vlist

        Dim objNf As New entidadeNf
        Dim repositorioNf As New repositorioNf

        Dim objNfTransicao As New entidadeNfTransicao
        Dim repositorioNfTransicao As New repositorioNfTransicao

        Try

            Me.lblInfo.Text = " Buscando as faturas por data leitura atual, aguarde... "
            Me.lblInfo.Refresh()

            With vLista
                .Items.Clear()
                .Columns.Clear()
                If .Columns.Count <= 1 Then
                    .Columns.Add("", "Leituras", CInt(VB6.TwipsToPixelsX(1500)))
                End If
            End With

            If pTabela = "NF" Then

                objNf.MESANOINI = Me.txtAno.Text & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex)
                objNf.MESANOFIM = Me.txtAno.Text & VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex)

                vlist = repositorioNf.SelectOthersTables_6(objNf)
            Else

                objNfTransicao.MESANOINI = Me.txtAno.Text & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex)
                objNfTransicao.MESANOFIM = Me.txtAno.Text & VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex)

                vlist = repositorioNfTransicao.SelectOthersTables_4(objNfTransicao)
            End If

            If vlist.Count > 0 Then

                BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 0, vlist.Count)

                Dim LVItem As ListViewItem = New ListViewItem()

                ' LVItem = vLista.Items.Add("Todas")

                If pTabela = "NF" Then

                    For Each objNfFor As entidadeNf In vlist
                        LVItem = vLista.Items.Add(objNfFor.DATALEIT)
                        BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 1)
                    Next

                Else

                    For Each objNfTransicaoFor As entidadeNfTransicao In vlist
                        LVItem = vLista.Items.Add(objNfTransicaoFor.DATALEIT)
                        BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 1)
                    Next

                End If

            End If

            Me.lblInfo.Text = ""
            Me.lblInfo.Refresh()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: PreencherListViewDataLeitura" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Public Sub PreencherListViewRotasPrefixo(ByRef vLista As System.Windows.Forms.ListView)

        Dim vlist

        Dim objNf As New entidadeNf
        Dim repositorioNf As New repositorioNf

        Try

            With vLista
                .Items.Clear()
                .Columns.Clear()
                If .Columns.Count <= 1 Then
                    .Columns.Add("", "Prefixo", CInt(VB6.TwipsToPixelsX(1000)))
                End If
            End With

            vlist = repositorioNf.SelectOthersTables_5(objNf)

            If vlist.Count > 0 Then

                Dim LVItem As ListViewItem = New ListViewItem()


                For Each objNfFor As entidadeNf In vlist
                    LVItem = vLista.Items.Add(objNfFor.ROTA_QUATRO)
                Next

            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: PreencherListViewRotasPrefixo" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Public Sub PreencherListViewCidade(ByRef vLista As System.Windows.Forms.ListView)

        Dim lstrCid As String
        Dim lstrZon As String
        Dim llngTam As Integer

        Dim vlist

        Dim objMunic As New entidadeMunic
        Dim repositorioMunic As New repositorioMunic

        Try


            With vLista

                .Items.Clear()
                .Columns.Clear()

                If .Columns.Count <= 1 Then
                    .Columns.Add("", "Nome", 160)
                    .Columns.Add("Zona", 50)
                End If

            End With

            vlist = repositorioMunic.Select_2(objMunic)

            If vlist.Count > 0 Then

                'With vLista
                '    .Items.Add("Marcar Todas")
                '    .Items.Item(.Items.Count - 1).SubItems.Add("")
                'End With


                For Each objMunicFor As entidadeMunic In vlist

                    lstrCid = Trim(IIf(IsDBNull(objMunicFor.NOME), "", objMunicFor.NOME))
                    lstrZon = Trim(IIf(IsDBNull(objMunicFor.ZONA), "", objMunicFor.ZONA))

                    With vLista
                        .Items.Add(lstrCid)
                        .Items.Item(.Items.Count - 1).SubItems.Add(lstrZon)
                    End With

                    If llngTam < Len(lstrCid) Then llngTam = Len(lstrCid)

                Next

                vLista.Columns.Item(1).Width = VB6.TwipsToPixelsX(llngTam * 200)
            End If

            'vLista.Items.Item(1).Font = VB6.FontChangeBold(vLista.Items.Item(1).Font, True)
            'vLista.Items.Item(1).Checked = True

            If vLista.Items.Count > 0 Then

                CheckAllListView(vLista, True)
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: PreencherListViewCidade" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub PegarFaixaRes(ByVal astrFaixa As String, ByVal amfgAux As AxMSFlexGridLib.AxMSFlexGrid)
        Dim lintPos1 As Short
        Dim lintPos2 As Short
        Dim llngIni As Integer
        Dim llngFim As Integer

        Try

            With amfgAux

                .Redraw = False
                .Clear()
                .AddItem("")
                .Rows = 0
                llngIni = 0
                llngFim = 0
                lintPos1 = 1
                lintPos2 = 0

                While lintPos1 <= Len(astrFaixa)
                    lintPos2 = InStr(lintPos1, astrFaixa, ";")
                    llngFim = Val(Mid(astrFaixa, lintPos1, lintPos2 - lintPos1))
                    .Rows = .Rows + 1
                    .set_TextMatrix(.Rows - 1, 0, llngIni)
                    .set_TextMatrix(.Rows - 1, 1, llngFim)

                    If llngIni < llngFim Then
                        llngIni = llngFim + 1
                    End If

                    lintPos1 = lintPos2 + 1

                End While

                .Redraw = True

            End With
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: PegarFaixaRes" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub LigDesObj(ByVal ablnModo As Boolean)

        Try

            Me.chkTrans.Enabled = IIf(Not iblnTotalizado, IIf(iblnAnual, False, ablnModo), False)
            Me.cmbSocios.Enabled = ablnModo
            Me.txtAno.Enabled = ablnModo
            Me.cmbMesIni.Enabled = IIf(iblnAnual, False, ablnModo)
            Me.cmbMesFim.Enabled = IIf(iblnAnual, False, ablnModo)
            Me.chkGrupoA.Enabled = ablnModo
            Me.chkGrupoB.Enabled = ablnModo
            Me.cmbRotaIni.Enabled = ablnModo
            Me.cmbRotaFim.Enabled = ablnModo
            Me.lsvRotas.Enabled = ablnModo
            Me.cmbModelo.Enabled = ablnModo
            Me.lvsCidades.Enabled = ablnModo
            Me.MSFGridRes.Enabled = ablnModo
            Me.MSFGridTarifa.Enabled = ablnModo
            Me.txtArq.Enabled = ablnModo
            Me.cmdPasta.Enabled = ablnModo
            Me.chkPreviaFat.Enabled = ablnModo
            ' Me.cmdExporta.Enabled = ablnModo
            Me.cmdImprimir.Enabled = ablnModo
            Me.cmdFechar.Enabled = ablnModo
            Me.chkRen863_2019.Enabled = ablnModo
            System.Windows.Forms.Application.DoEvents()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: LigDesObj" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Public Sub SetaDados(ByVal astrTabelaNf As String, ByVal ablnConferencia As Boolean, ByVal ablnAnual As Boolean)

        Try

            istrTabNf = astrTabelaNf
            iblnTotalizado = ablnConferencia
            Me.chkTrans.Enabled = (Not ablnConferencia)
            iblnAnual = ablnAnual

            If ablnConferencia Then

                Me.Text = "Relatório de Conferência"
                Me.chkTrans.CheckState = IIf(ablnConferencia, System.Windows.Forms.CheckState.Checked, System.Windows.Forms.CheckState.Unchecked)
                frmPrincipal.mnuRelatorio_ConferenciaFaturamento.Enabled = False
                Me.chkPreviaFat.Visible = True

            ElseIf ablnAnual Then

                Me.Text = "Relatório Anual do Fechamento de Faturamento"
                Me.cmbMesIni.SelectedIndex = 0
                Me.cmbMesFim.SelectedIndex = Me.cmbMesFim.Items.Count - 1
                frmPrincipal.mnuRelatorio_Fechamento_TotalFaturamentoAnual.Enabled = False
                Me.cmbMesIni.Enabled = False
                Me.cmbMesFim.Enabled = False
                Me.chkTrans.Enabled = False

            Else
                Me.Text = "Relatório de Fechamento de Faturamento"
            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: SetaDados" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Function LimpaCols() As Object

        Dim lintLin As Short
        Dim lintCol As Short

        Try

            iblnQuebra = False
            For lintCol = 1 To 4
                For lintLin = 1 To 30
                    strCol(lintCol, lintLin) = ""
                Next lintLin
            Next lintCol


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: LimpaCols" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Function
        End Try

    End Function

    Private Function GetFiltroPrefixo() As String

        Dim lblnSelecionou As Boolean
        Dim llngMenor As Integer
        Dim llngMaior As Integer
        Dim llngAux As Integer
        Dim lstrRet As String
        Dim llngIdx As Integer

        Try

            lstrRet = ""
            llngMenor = 99
            llngMaior = 0
            lblnSelecionou = False
            With Me.lsvRotas
                For llngIdx = 1 To .Items.Count
                    If .Items.Item(llngIdx - 1).Checked = True Then
                        lblnSelecionou = True
                        llngAux = CInt(.Items.Item(llngIdx - 1).Text)
                        If llngAux <= llngMenor Then
                            llngMenor = llngAux
                        End If
                        If llngAux >= llngMaior Then
                            llngMaior = llngAux
                        End If
                    End If
                Next llngIdx
            End With
            If lblnSelecionou Then
                lstrRet = VB6.Format(llngMenor, "00") & "-" & VB6.Format(llngMaior, "00")
            Else
                lstrRet = ""
            End If
            GetFiltroPrefixo = lstrRet

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: GetFiltroPrefixo" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Function
        End Try

    End Function

    Private Function CriaTabelas(ByRef astrSqlPri As String, ByRef astrSqlIte As String, ByRef aboolCriarTabela As Boolean, ByRef aboolCriarSqlPri As Boolean, ByRef aboolCriarSqlIte As Boolean) As Boolean

        Dim lblnRet As Boolean

        Dim objTempEstatisItens As New entidadeTempEstatisItens
        Dim repositorioTempEstatisItens As New repositorioTempEstatisItens

        Dim objTempEstatis As New entidadeTempEstatis
        Dim repositorioTempEstatis As New repositorioTempEstatis

        Try

            lblnRet = False

            If aboolCriarTabela = True Then

                'Dropa a tabela caso exista
                objTempEstatis.TABLE = istrTabTemp
                objTempEstatisItens.TABLE = istrTabTempItens

                repositorioTempEstatis.Execute_1(objTempEstatis)
                repositorioTempEstatisItens.Execute_1(objTempEstatisItens)

                repositorioTempEstatis.Execute(objTempEstatis)
                repositorioTempEstatisItens.Execute(objTempEstatisItens)


                lblnRet = True

            Else
                lblnRet = True
            End If


            If lblnRet Then

                'PREPARA CONTROLE DE INSERCAO TEMPORARIO NO MYSQL

                If aboolCriarSqlIte = True Then
                    astrSqlIte = "INSERT INTO " & istrTabTempItens & " (CODIGO, NOME, VALOR, ZONA, GRUPO) VALUES "
                End If

                If aboolCriarSqlPri = True Then

                    astrSqlPri = "INSERT INTO " & istrTabTemp & " (CLASSE, "
                    'CONVENCIONAL
                    'QTDE
                    astrSqlPri = astrSqlPri & "QKWH_CONS, QKWH_FAT, QKWH_FAT_BAN, QKW_CONTR, QKW_FAT, "
                    'VALOR
                    astrSqlPri = astrSqlPri & "VKWH_CONS, VKWH_FAT, VKWH_FAT_BAN, VKW_FAT, VCONREAT, VDEMREAT, "
                    'HOROSAZONAL
                    'QTDE
                    astrSqlPri = astrSqlPri & "QKWH_FAT_P,QKWH_FAT_I, QKWH_FAT_FP, QKWH_FAT_P_BAN, QKWH_FAT_I_BAN, QKWH_FAT_FP_BAN, QKWH_FAT_P_LIV, QKWH_FAT_FP_LIV, "
                    astrSqlPri = astrSqlPri & "QKWH_DEV_P, QKWH_DEV_FP, QKWH_UTR_P, QKWH_UTR_FP, QKW_CONTR_P, QKW_CONTR_FP, "
                    astrSqlPri = astrSqlPri & "QKW_FAT_P, QKW_FAT_FP, QKW_DIF_FAT_P, QKW_DIF_FAT_FP, QKW_FATU_P, QKW_FATU_FP, "
                    'VALOR
                    astrSqlPri = astrSqlPri & "VKWH_FAT_P, VKWH_FAT_I, VKWH_FAT_FP, VKWH_FAT_P_BAN, VKWH_FAT_I_BAN, VKWH_FAT_FP_BAN, VKWH_FAT_P_LIV, VKWH_FAT_FP_LIV, "
                    astrSqlPri = astrSqlPri & "VKWH_DEV_P, VKWH_DEV_FP, VKWH_UTR_P, VKWH_UTR_FP, VKW_FAT_P, VKW_FAT_FP, VKW_DIF_FAT_P, VKW_DIF_FAT_FP, VKW_FATU_P, VKW_FATU_FP, "
                    astrSqlPri = astrSqlPri & "VKW_DSC_PROV, VKW_DSC_REAL, VKW_DEV_CCEE, VKW_COB_CCEE,VKWH_DSC_PROV, VKWH_DSC_REAL, VKWH_DEV_CCEE, VKWH_COB_CCEE, "
                    'REATIVO
                    astrSqlPri = astrSqlPri & "VCONREAT_P, VCONREAT_FP, VDEMREAT_P, VDEMREAT_FP, "
                    'MICRO GERAÇÃO
                    'ASTRSQLPRI = ASTRSQLPRI & "QKWH_REVERSO, VKWH_REVERSO, QKWH_REVERSOP, QKWH_REVERSOFP, VKWH_REVERSOP, VKWH_REVERSOFP, "
                    astrSqlPri = astrSqlPri & "QKWH_REVERSOP, QKWH_REVERSOI, QKWH_REVERSOFP, VKWH_REVERSOP, VKWH_REVERSOI, VKWH_REVERSOFP, QKWH_REVERSOP_SEFAZ, QKWH_REVERSOI_SEFAZ, QKWH_REVERSOFP_SEFAZ, VKWH_REVERSOP_SEFAZ, VKWH_REVERSOI_SEFAZ, VKWH_REVERSOFP_SEFAZ,"
                    'OUTROS
                    astrSqlPri = astrSqlPri & "TIP, SLD_ARRED, ENC_FINAN, ICMS, PIS, COFINS, "
                    'TRIBUTACAO COMERCIALIZADOR USADO PARA O LIVRE
                    astrSqlPri = astrSqlPri & "ICMS_ST, PIS_ST, COFINS_ST, "
                    'BASE DE CALCULO
                    astrSqlPri = astrSqlPri & "BASEICMS, BASEPIS, BASECOFINS, ICMSPISCOF, ISENTOICMS, DIFERIDO, "
                    '
                    astrSqlPri = astrSqlPri & "DIF_ELTRBR, JUROS, ENCARGO, MUST, TOTAL, TAXADOS, DIVERSOS, CONVENIOS, DESCONTOS, DESCONTOS_1, RETENCAO, FLGMEDFAT, FATURA_FINAL, IRRIGACAO_AQUICULTURA, "
                    astrSqlPri = astrSqlPri & "MICRO_GERACAO, MICRO_GERACAO_DISTRIBUIDA, MICRO_GERACAO_CONVENIO_SEFAZ, TARIFA_BRANCA, VKWH_REVERSO_IMPORTE, "
                    astrSqlPri = astrSqlPri & "FLGST, FASE, GRUPO, ZONA, LIVRO,CONTA, NOME, GRUPOT, SEQUENCIA, MESANO, MATRICULA, NUMNF, grupo_tarifario, classe_faturada, descricao_classe,mesano_referencia,anomes_fat, "
                    astrSqlPri = astrSqlPri & "DATA_EMISSAO, DATA_APRESENTACAO,data_vencimento,data_leitura_atual, data_leitura_anterior,  "

                    astrSqlPri = astrSqlPri & "valor_juros_ece, valor_diferenca_ece, valor_ece, valor_liquido, "

                    astrSqlPri = astrSqlPri & "qtde_fx1, qtde_fx2, qtde_fx3, qtde_fx4, "
                    astrSqlPri = astrSqlPri & "vlr_fx1, vlr_fx2, vlr_fx3, vlr_fx4, "

                    astrSqlPri = astrSqlPri & "kwh_lido, base_icms_1, aliquota_icms_1, valor_icms_1, base_icms_2, "
                    astrSqlPri = astrSqlPri & "aliquota_icms_2, valor_icms_2, "
                    astrSqlPri = astrSqlPri & "Aliquota_PIS, Aliquota_COFINS, "
                    astrSqlPri = astrSqlPri & "receitas_financeiras, ressarcimento_idqual, "

                    astrSqlPri = astrSqlPri & "valor_encargo_uso_sis_trans, "
                    astrSqlPri = astrSqlPri & "desconto_must, "
                    astrSqlPri = astrSqlPri & "encargo_kwh_faturado_ponta, "
                    astrSqlPri = astrSqlPri & "encargo_valor_kwh_faturado_ponta, "
                    astrSqlPri = astrSqlPri & "encargo_kwh_faturado_fora_ponta, "
                    astrSqlPri = astrSqlPri & "encargo_valor_kwh_faturado_fora_ponta, "
                    astrSqlPri = astrSqlPri & "mwh_medio, "
                    astrSqlPri = astrSqlPri & "mwh_medio_horas, "

                    astrSqlPri = astrSqlPri & "VALOR_REVERSO, "
                    astrSqlPri = astrSqlPri & "VALOR_REVERSO_BAN, "
                    astrSqlPri = astrSqlPri & "REVERSO_PONTA, "
                    astrSqlPri = astrSqlPri & "REVERSO_PONTA_BANDEIRA, "
                    astrSqlPri = astrSqlPri & "REVERSO_FORA_DE_PONTA, "
                    astrSqlPri = astrSqlPri & "REVERSO_FORA_DE_PONTA_BANDEIRA, "
                    astrSqlPri = astrSqlPri & "bandeira_vlr_kwh_fat, "
                    astrSqlPri = astrSqlPri & "bandeira_valor_kwh_fat_ponta, "
                    astrSqlPri = astrSqlPri & "bandeira_valor_kwh_fat_fora_ponta, "
                    astrSqlPri = astrSqlPri & "valor_energia_desconto_provisorio,  "

                    astrSqlPri = astrSqlPri & "valor_energia_desconto_realizado, "
                    astrSqlPri = astrSqlPri & "valor_energia_devolucao_diferenca_ccee, "
                    astrSqlPri = astrSqlPri & "valor_energia_cobranca_diferenca_ccee, "
                    astrSqlPri = astrSqlPri & "CONSUMO_PONTA, "
                    astrSqlPri = astrSqlPri & "CONSUMO_FORA_PONTA,  " 

                    astrSqlPri = astrSqlPri & "REVERSO_FORA_PONTA, "
                    astrSqlPri = astrSqlPri & "REVERSO_RESIDUO_FORA_PONTA, "
                    astrSqlPri = astrSqlPri & "TUSD, "
                    astrSqlPri = astrSqlPri & "CONSUMO_MEDIDO, "
                    astrSqlPri = astrSqlPri & "REVERSO_LIDO, "

                    astrSqlPri = astrSqlPri & "datast, "
                    astrSqlPri = astrSqlPri & "data_pagamento ) VALUES "

                End If

            End If

            CriaTabelas = lblnRet

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: CriaTabelas" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Function
        End Try

    End Function

    Private Function MontaLinhasCsv(ByRef objTempEstatis As entidadeTempEstatis) As String

        Dim lstrLin As String
        Dim llngQtdconsumidores As Integer
        Dim lstrZona As String
        Dim lstrLivro As String
        Dim lstrConta As String
        Dim lstrNome As String

        Dim ldblQtdkWhLido As Double
        Dim ldblTotQtdkWhFaturado As Double
        Dim ldblQtdkWhFaturado As Double
        Dim ldblQtdkWhFaturadoPonta As Double
        Dim ldblQtdkWhFaturadoForaPonta As Double
        Dim ldblQtdkWhDevolvidoPonta As Double
        Dim ldblQtdkWhDevolvidoForaPonta As Double
        Dim ldblQtdkWhUltrapassadoPonta As Double
        Dim ldblQtdkWhUltrapassadoForaPonta As Double

        Dim ldblVlrkWhLido As Double
        Dim ldblTotVlrkWhFaturado As Double
        Dim ldblVlrkWhFaturado As Double
        Dim ldblVlrkWhFaturadoPonta As Double
        Dim ldblVlrkWhFaturadoForaPonta As Double
        Dim ldblVlrkWhDevolvidoPonta As Double
        Dim ldblVlrkWhDevolvidoForaPonta As Double
        Dim ldblVlrkWhUltrapassadoPonta As Double
        Dim ldblVlrkWhUltrapassadoForaPonta As Double

        Dim ldblVlrkWhReativo As Double
        Dim ldblVlrkWhReativoPonta As Double
        Dim ldblVlrkWhReativoForaPonta As Double
        Dim ldblVlrkWReativo As Double
        Dim ldblVlrkWReativoPonta As Double
        Dim ldblVlrkWReativoForaPonta As Double

        Dim ldblTotQtdkWFaturado As Double
        Dim ldblQtdkWFaturado As Double
        Dim ldblQtdkWContratado As Double
        Dim ldblQtdkWFaturadoPonta As Double
        Dim ldblQtdkWFaturadoForaPonta As Double
        Dim ldblQtdkWContratadoPonta As Double
        Dim ldblQtdkWContratadoForaPonta As Double
        Dim ldblQtdkWUltrapassadoPonta As Double
        Dim ldblQtdkWUltrapassadoForaPonta As Double

        Dim ldblTotVlrkWFaturado As Double
        Dim ldblVlrkWFaturado As Double
        Dim ldblVlrkWFaturadoPonta As Double
        Dim ldblVlrkWFaturadoForaPonta As Double
        Dim ldblVlrkWUltrapassadoPonta As Double
        Dim ldblVlrkWUltrapassadoForaPonta As Double

        Dim ldblVlrkWDescontoProvisorio As Double
        Dim ldblVlrkWDescontoRealizado As Double
        Dim ldblVlrkWDevolvidoCCEE As Double
        Dim ldblVlrkWCobrancaCCEE As Double

        Dim ldblVlrCip As Double
        Dim ldblVlrSaldoArredondamento As Double
        Dim ldblVlrEncargoFinanceiro As Double
        Dim ldblVlrDiferecaEletrobras As Double
        Dim ldblVlrJuros As Double
        Dim ldblVlrEncargo As Double
        Dim ldblVlrMust As Double
        Dim ldblVlrConvenios As Double
        Dim ldblVlrDescontos As Double
        Dim ldblVlrRetencao As Double
        Dim ldblVlrDiversos As Double
        Dim ldblVlrTaxados As Double

        Dim ldblVlrIcms As Double
        Dim ldblVlrPis As Double
        Dim ldblVlrCofins As Double
        Dim ldblVlrBaseIcms As Double
        Dim ldblVlrBasePis As Double
        Dim ldblVlrBaseCofins As Double
        Dim ldblVlrIcmsPisCof As Double

        Dim ldblRecCompa As Double
        Dim ldblImporte As Double
        Dim ldblVlrTotal As Double

        Try


            'llngQtdconsumidores = IIf(IsNull(objTempEstatis.qtd_consumidores), 0, objTempEstatis.qtd_consumidores)
            ldblQtdkWhLido = IIf(IsDBNull(objTempEstatis.QKWH_CONS), 0, objTempEstatis.QKWH_CONS)
            ldblQtdkWhFaturado = IIf(IsDBNull(objTempEstatis.QKWH_FAT), 0, objTempEstatis.QKWH_FAT)
            ldblQtdkWhFaturadoPonta = IIf(IsDBNull(objTempEstatis.QKWH_FAT_P), 0, objTempEstatis.QKWH_FAT_P)
            ldblQtdkWhFaturadoForaPonta = IIf(IsDBNull(objTempEstatis.QKWH_FAT_FP), 0, objTempEstatis.QKWH_FAT_FP)
            ldblQtdkWhDevolvidoPonta = IIf(IsDBNull(objTempEstatis.QKWH_DEV_P), 0, objTempEstatis.QKWH_DEV_P)
            ldblQtdkWhDevolvidoForaPonta = IIf(IsDBNull(objTempEstatis.QKWH_DEV_FP), 0, objTempEstatis.QKWH_DEV_FP)
            ldblQtdkWhUltrapassadoPonta = IIf(IsDBNull(objTempEstatis.QKWH_UTR_P), 0, objTempEstatis.QKWH_UTR_P)
            ldblQtdkWhUltrapassadoForaPonta = IIf(IsDBNull(objTempEstatis.QKWH_UTR_FP), 0, objTempEstatis.QKWH_UTR_FP)
            ldblVlrkWhLido = IIf(IsDBNull(objTempEstatis.VKWH_CONS), 0, objTempEstatis.VKWH_CONS)
            ldblVlrkWhFaturado = IIf(IsDBNull(objTempEstatis.VKWH_FAT), 0, objTempEstatis.VKWH_FAT)
            ldblVlrkWhFaturadoPonta = IIf(IsDBNull(objTempEstatis.VKWH_FAT_P), 0, objTempEstatis.VKWH_FAT_P)
            ldblVlrkWhFaturadoForaPonta = IIf(IsDBNull(objTempEstatis.VKWH_FAT_FP), 0, objTempEstatis.VKWH_FAT_FP)
            ldblVlrkWhDevolvidoPonta = IIf(IsDBNull(objTempEstatis.VKWH_DEV_P), 0, objTempEstatis.VKWH_DEV_P)
            ldblVlrkWhDevolvidoForaPonta = IIf(IsDBNull(objTempEstatis.VKWH_DEV_FP), 0, objTempEstatis.VKWH_DEV_FP)
            ldblVlrkWhUltrapassadoPonta = IIf(IsDBNull(objTempEstatis.VKWH_UTR_P), 0, objTempEstatis.VKWH_UTR_P)
            ldblVlrkWhUltrapassadoForaPonta = IIf(IsDBNull(objTempEstatis.VKWH_UTR_FP), 0, objTempEstatis.VKWH_UTR_FP)
            ldblVlrkWhReativo = IIf(IsDBNull(objTempEstatis.VCONREAT), 0, objTempEstatis.VCONREAT)
            ldblVlrkWhReativoPonta = IIf(IsDBNull(objTempEstatis.VCONREAT_P), 0, objTempEstatis.VCONREAT_P)
            ldblVlrkWhReativoForaPonta = IIf(IsDBNull(objTempEstatis.VCONREAT_FP), 0, objTempEstatis.VCONREAT_FP)
            ldblVlrkWReativo = IIf(IsDBNull(objTempEstatis.VDEMREAT), 0, objTempEstatis.VDEMREAT)
            ldblVlrkWReativoPonta = IIf(IsDBNull(objTempEstatis.VDEMREAT_P), 0, objTempEstatis.VDEMREAT_P)
            ldblVlrkWReativoForaPonta = IIf(IsDBNull(objTempEstatis.VDEMREAT_FP), 0, objTempEstatis.VDEMREAT_FP)
            ldblQtdkWFaturado = IIf(IsDBNull(objTempEstatis.QKW_FAT), 0, objTempEstatis.QKW_FAT)
            ldblQtdkWContratado = IIf(IsDBNull(objTempEstatis.QKW_CONTR), 0, objTempEstatis.QKW_CONTR)
            ldblQtdkWFaturadoPonta = IIf(IsDBNull(objTempEstatis.QKW_FAT_P), 0, objTempEstatis.QKW_FAT_P)
            ldblQtdkWFaturadoForaPonta = IIf(IsDBNull(objTempEstatis.QKW_FAT_FP), 0, objTempEstatis.QKW_FAT_FP)
            ldblQtdkWContratadoPonta = IIf(IsDBNull(objTempEstatis.QKW_CONTR_P), 0, objTempEstatis.QKW_CONTR_P)
            ldblQtdkWContratadoForaPonta = IIf(IsDBNull(objTempEstatis.QKW_CONTR_FP), 0, objTempEstatis.QKW_CONTR_FP)
            ldblQtdkWUltrapassadoPonta = IIf(IsDBNull(objTempEstatis.QKW_FATU_P), 0, objTempEstatis.QKW_FATU_P)
            ldblQtdkWUltrapassadoForaPonta = IIf(IsDBNull(objTempEstatis.QKW_FATU_FP), 0, objTempEstatis.QKW_FATU_FP)
            ldblVlrkWFaturado = IIf(IsDBNull(objTempEstatis.VKW_FAT), 0, objTempEstatis.VKW_FAT)
            ldblVlrkWFaturadoPonta = IIf(IsDBNull(objTempEstatis.VKW_FAT_P), 0, objTempEstatis.VKW_FAT_P)
            ldblVlrkWFaturadoForaPonta = IIf(IsDBNull(objTempEstatis.VKW_FAT_FP), 0, objTempEstatis.VKW_FAT_FP)
            ldblVlrkWUltrapassadoPonta = IIf(IsDBNull(objTempEstatis.VKW_FATU_P), 0, objTempEstatis.VKW_FATU_P)
            ldblVlrkWUltrapassadoForaPonta = IIf(IsDBNull(objTempEstatis.VKW_FATU_FP), 0, objTempEstatis.VKW_FATU_FP)
            ldblVlrkWDescontoProvisorio = IIf(IsDBNull(objTempEstatis.VKW_DSC_PROV), 0, objTempEstatis.VKW_DSC_PROV)
            ldblVlrkWDescontoRealizado = IIf(IsDBNull(objTempEstatis.VKW_DSC_REAL), 0, objTempEstatis.VKW_DSC_REAL)
            ldblVlrkWDevolvidoCCEE = IIf(IsDBNull(objTempEstatis.VKW_DEV_CCEE), 0, objTempEstatis.VKW_DEV_CCEE)
            ldblVlrkWCobrancaCCEE = IIf(IsDBNull(objTempEstatis.VKW_COB_CCEE), 0, objTempEstatis.VKW_COB_CCEE)
            ldblVlrCip = IIf(IsDBNull(objTempEstatis.TIP), 0, objTempEstatis.TIP)
            ldblVlrSaldoArredondamento = IIf(IsDBNull(objTempEstatis.SLD_ARRED), 0, objTempEstatis.SLD_ARRED)
            ldblVlrEncargoFinanceiro = IIf(IsDBNull(objTempEstatis.ENC_FINAN), 0, objTempEstatis.ENC_FINAN)
            ldblVlrDiferecaEletrobras = IIf(IsDBNull(objTempEstatis.DIF_ELTRBR), 0, objTempEstatis.DIF_ELTRBR)
            ldblVlrJuros = IIf(IsDBNull(objTempEstatis.JUROS), 0, objTempEstatis.JUROS)
            ldblVlrEncargo = IIf(IsDBNull(objTempEstatis.ENCARGO), 0, objTempEstatis.ENCARGO)
            ldblVlrMust = IIf(IsDBNull(objTempEstatis.MUST), 0, objTempEstatis.MUST)
            ldblVlrConvenios = IIf(IsDBNull(objTempEstatis.CONVENIOS), 0, objTempEstatis.CONVENIOS)
            ldblVlrDescontos = IIf(IsDBNull(objTempEstatis.DESCONTOS), 0, objTempEstatis.DESCONTOS)
            ldblVlrRetencao = IIf(IsDBNull(objTempEstatis.RETENCAO), 0, objTempEstatis.RETENCAO)
            ldblVlrDiversos = IIf(IsDBNull(objTempEstatis.DIVERSOS), 0, objTempEstatis.DIVERSOS)
            ldblVlrTaxados = IIf(IsDBNull(objTempEstatis.TAXADOS), 0, objTempEstatis.TAXADOS)
            ldblVlrIcms = IIf(IsDBNull(objTempEstatis.ICMS), 0, objTempEstatis.ICMS)
            ldblVlrPis = IIf(IsDBNull(objTempEstatis.PIS), 0, objTempEstatis.PIS)
            ldblVlrCofins = IIf(IsDBNull(objTempEstatis.COFINS), 0, objTempEstatis.COFINS)
            ldblVlrBaseIcms = IIf(IsDBNull(objTempEstatis.BASEICMS), 0, objTempEstatis.BASEICMS)
            ldblVlrBasePis = IIf(IsDBNull(objTempEstatis.BASEPIS), 0, objTempEstatis.BASEPIS)
            ldblVlrBaseCofins = IIf(IsDBNull(objTempEstatis.BASECOFINS), 0, objTempEstatis.BASECOFINS)
            ldblVlrIcmsPisCof = IIf(IsDBNull(objTempEstatis.ICMSPISCOF), 0, objTempEstatis.ICMSPISCOF)
            ldblVlrTotal = IIf(IsDBNull(objTempEstatis.TOTAL), 0, objTempEstatis.TOTAL)
            lstrZona = IIf(IsDBNull(objTempEstatis.ZONA), "", objTempEstatis.ZONA)
            lstrLivro = IIf(IsDBNull(objTempEstatis.LIVRO), "", objTempEstatis.LIVRO)
            lstrConta = IIf(IsDBNull(objTempEstatis.CONTA), "", objTempEstatis.CONTA)
            lstrNome = IIf(IsDBNull(objTempEstatis.NOME), "", objTempEstatis.NOME)

            'lstrLin = lstrLin & Strings.FormatNumber(llngQtdconsumidores, 0) & ";"
            'lstrLin = lstrLin & Strings.FormatNumber(llngQtdconsumidores, 0) & ";"
            lstrLin = lstrLin & lstrZona & ";" & lstrLivro & ";" & lstrConta & ";" & lstrNome & ";"

            lstrLin = lstrLin & FormatNumber(ldblVlrkWhReativoPonta, 2) & ";" & FormatNumber(ldblVlrkWhReativoForaPonta + ldblVlrkWhReativo, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblVlrkWReativoPonta, 2) & ";" & FormatNumber(ldblVlrkWReativoForaPonta + ldblVlrkWReativo, 2) & ";"

            ldblTotQtdkWhFaturado = (ldblQtdkWhFaturado + ldblQtdkWhFaturadoPonta + ldblQtdkWhFaturadoForaPonta + ldblQtdkWhUltrapassadoPonta + ldblQtdkWhUltrapassadoForaPonta) + (ldblQtdkWhDevolvidoPonta + ldblQtdkWhDevolvidoForaPonta)
            ldblTotVlrkWhFaturado = (ldblVlrkWhFaturado + ldblVlrkWhFaturadoPonta + ldblVlrkWhFaturadoForaPonta + ldblVlrkWhUltrapassadoPonta + ldblVlrkWhUltrapassadoForaPonta) + (ldblVlrkWhDevolvidoPonta + ldblVlrkWhDevolvidoForaPonta)
            lstrLin = lstrLin & FormatNumber(ldblQtdkWhLido, 0) & ";" & FormatNumber(ldblTotQtdkWhFaturado, 0) & ";" & FormatNumber(ldblTotVlrkWhFaturado, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblQtdkWhFaturadoPonta, 0) & ";" & FormatNumber(ldblVlrkWhFaturadoPonta, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblQtdkWhFaturadoForaPonta, 0) & ";" & FormatNumber(ldblVlrkWhFaturadoForaPonta, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblQtdkWhDevolvidoPonta, 0) & ";" & FormatNumber(ldblVlrkWhDevolvidoPonta, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblQtdkWhDevolvidoForaPonta, 0) & ";" & FormatNumber(ldblVlrkWhDevolvidoForaPonta, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblQtdkWhUltrapassadoPonta, 0) & ";" & FormatNumber(ldblVlrkWhUltrapassadoPonta, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblQtdkWhUltrapassadoForaPonta, 0) & ";" & FormatNumber(ldblVlrkWhUltrapassadoForaPonta, 2) & ";"

            ldblTotQtdkWFaturado = (ldblQtdkWFaturado + ldblQtdkWFaturadoPonta + ldblQtdkWFaturadoForaPonta + ldblQtdkWUltrapassadoPonta + ldblQtdkWUltrapassadoForaPonta)
            ldblTotVlrkWFaturado = (ldblVlrkWFaturado + ldblVlrkWFaturadoPonta + ldblVlrkWFaturadoForaPonta + ldblVlrkWUltrapassadoPonta + ldblVlrkWUltrapassadoForaPonta)
            lstrLin = lstrLin & FormatNumber(ldblTotQtdkWFaturado, 0) & ";" & FormatNumber(ldblTotVlrkWFaturado, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblQtdkWFaturadoPonta, 0) & ";" & FormatNumber(ldblVlrkWFaturadoPonta, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblQtdkWFaturadoForaPonta, 0) & ";" & FormatNumber(ldblVlrkWFaturadoForaPonta, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblQtdkWUltrapassadoPonta, 0) & ";" & FormatNumber(ldblVlrkWUltrapassadoPonta, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblQtdkWUltrapassadoForaPonta, 0) & ";" & FormatNumber(ldblVlrkWUltrapassadoForaPonta, 2) & ";"

            lstrLin = lstrLin & FormatNumber(ldblVlrkWDescontoProvisorio, 2) & ";" & FormatNumber(ldblVlrkWDescontoRealizado, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblVlrkWDevolvidoCCEE, 2) & ";" & FormatNumber(ldblVlrkWCobrancaCCEE, 2) & ";"

            lstrLin = lstrLin & FormatNumber(ldblVlrConvenios, 2) & ";" & FormatNumber(ldblVlrDiversos, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblVlrTaxados, 2) & ";" & FormatNumber(ldblVlrDescontos, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblVlrEncargoFinanceiro, 2) & ";" & FormatNumber(ldblVlrRetencao, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblVlrCip, 2) & ";" & FormatNumber(ldblVlrJuros, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblVlrDiferecaEletrobras, 2) & ";" & FormatNumber(ldblVlrEncargo, 2) & ";"
            lstrLin = lstrLin & FormatNumber(ldblVlrMust, 2) & ";"

            lstrLin = lstrLin & FormatNumber(ldblVlrIcms, 2) & ";" & FormatNumber(ldblVlrPis, 2) & ";" & FormatNumber(ldblVlrCofins, 2) & ";"

            ldblRecCompa = ldblTotVlrkWhFaturado + ldblTotVlrkWFaturado
            ldblRecCompa = ldblRecCompa + ldblVlrkWhReativo + ldblVlrkWhReativoPonta + ldblVlrkWhReativoForaPonta + ldblVlrkWReativo + ldblVlrkWReativoPonta + ldblVlrkWReativoForaPonta
            ldblRecCompa = ldblRecCompa + ((ldblVlrDiversos + ldblVlrEncargoFinanceiro + ldblVlrTaxados) - ldblVlrDescontos)
            ldblRecCompa = ldblRecCompa + (ldblVlrkWCobrancaCCEE - (ldblVlrkWDescontoProvisorio + ldblVlrkWDescontoRealizado + ldblVlrkWDevolvidoCCEE))
            ldblImporte = ldblTotVlrkWhFaturado + ldblTotVlrkWFaturado
            ldblImporte = ldblImporte + ldblVlrkWhReativo + ldblVlrkWhReativoPonta + ldblVlrkWhReativoForaPonta + ldblVlrkWReativo + ldblVlrkWReativoPonta + ldblVlrkWReativoForaPonta
            ldblImporte = ldblImporte + (ldblVlrIcms + ldblVlrPis + ldblVlrCofins)
            ldblImporte = ldblImporte + (ldblVlrkWCobrancaCCEE - (ldblVlrkWDescontoProvisorio + ldblVlrkWDescontoRealizado + ldblVlrkWDevolvidoCCEE))
            lstrLin = lstrLin & FormatNumber(ldblRecCompa, 2) & ";" & FormatNumber(ldblImporte, 2) & ";" & FormatNumber(ldblVlrTotal, 2) & ";"

            'Contrato
            lstrLin = lstrLin & FormatNumber(ldblQtdkWContratado, 0) & ";"
            lstrLin = lstrLin & FormatNumber(ldblQtdkWContratadoPonta, 0) & ";"
            lstrLin = lstrLin & FormatNumber(ldblQtdkWContratadoForaPonta, 0) & ";"

            MontaLinhasCsv = lstrLin


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: MontaLinhasCsv" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Function
        End Try

    End Function

    Private Function MontaTabela(ByVal astrFiltro_Zona As String) As Boolean

        Dim lstrFilPref As String
        Dim lblnControl As Boolean 'Controle de socios, não socios ou todos
        Dim lblnRetorno As Boolean
        Dim ldteIni As Date
        Dim ldteFim As Date
        Dim ldteFimLeit As Date
        Dim lstrMesAno As String
        Dim lintContInsertPri As Short
        Dim lintContInsertItens As Short
        '
        Dim lstrItens As String
        Dim lstrClasse As String
        Dim lstrZona As String
        Dim lstrLivro As String
        Dim lstrConta As String
        Dim lstrNome As String
        Dim llngUnidId As Integer
        Dim llngConsId As Integer
        Dim lstrGrupo As String
        Dim lstrGrupoT As String
        Dim lintLivreEspecial As Short
        Dim lintParcialmenteCativo As Short
        Dim lintLivreVerde As Short
        Dim lintIrrigacaoAquicultura As Integer
        Dim lintMicroGeracaoConvenioSefaz As Short
        Dim lintTarifaBranca As Short
        Dim lstrFlgSt As String
        Dim ldteFlgSt As Date
        Dim ldteEmissao As Date
        Dim ldteApresentacao As Date
        Dim lintMpr As Short 'Usado para caso tiver alguma fatura cancelada no mês de faturamento de outro mês
        Dim lstrFase As String
        Dim lblnInclui As Boolean
        Dim ldblValorTot As Double
        Dim llngMatricula As Integer
        Dim lstrFlgMedFat As String
        Dim lintFaturaFinal As String
        Dim lintMicroGeracao As Short
        Dim lintMicroGeracaoDistribuida As Short
        Dim dNumNf As Double
        Dim sGrupo_tarifario As String
        Dim sClasse_faturada As String
        Dim sDescricao_classe As String
        Dim sMesano_referencia As String
        Dim sAnomes_fat As String
        Dim dData_emissao As Date
        Dim dData_apresentacao As Date
        Dim dData_vencimento As Date
        Dim dData_leitura_atual As Date
        Dim dData_leitura_anterior As Date


        Dim dvalor_juros_ece As Double
        Dim dvalor_diferenca_ece As Double
        Dim dvalor_ece As Double
        Dim dvalor_liquido As Double

        Dim dqtde_fx1 As Double
        Dim dqtde_fx2 As Double
        Dim dqtde_fx3 As Double
        Dim dqtde_fx4 As Double
        Dim dvlr_fx1 As Double
        Dim dvlr_fx2 As Double
        Dim dvlr_fx3 As Double
        Dim dvlr_fx4 As Double

        Dim dkwh_lido As Double
        Dim dbase_icms_1 As Double
        Dim daliquota_icms_1 As Double
        Dim dvalor_icms_1 As Double
        Dim dbase_icms_2 As Double
        Dim daliquota_icms_2 As Double
        Dim dvalor_icms_2 As Double
        Dim dAliquota_PIS As Double
        Dim dAliquota_COFINS As Double
        Dim dreceitas_financeiras As Double
        Dim dressarcimento_idqual As Double

        Dim dvalor_encargo_uso_sis_trans As Double
        Dim ddesconto_must As Double
        Dim dencargo_kwh_faturado_ponta As Double
        Dim dencargo_valor_kwh_faturado_ponta As Double
        Dim dencargo_kwh_faturado_fora_ponta As Double
        Dim dencargo_valor_kwh_faturado_fora_ponta As Double
        Dim dmwh_medio As Double
        Dim dmwh_medio_horas As Double

        Dim dVALOR_REVERSO As Double
        Dim dVALOR_REVERSO_BAN As Double
        Dim dREVERSO_PONTA As Double
        Dim dREVERSO_PONTA_BANDEIRA As Double
        Dim dREVERSO_FORA_DE_PONTA As Double
        Dim dREVERSO_FORA_DE_PONTA_BANDEIRA As Double
        Dim dbandeira_vlr_kwh_fat As Double
        Dim dbandeira_valor_kwh_fat_ponta As Double
        Dim dbandeira_valor_kwh_fat_fora_ponta As Double
        Dim dvalor_energia_desconto_provisorio As Double

        Dim dvalor_energia_desconto_realizado As Double
        Dim dvalor_energia_devolucao_diferenca_ccee As Double
        Dim dvalor_energia_cobranca_diferenca_ccee As Double
        Dim dCONSUMO_PONTA As Double
        Dim dCONSUMO_FORA_PONTA As Double

        Dim dREVERSO_FORA_PONTA As Double
        Dim dREVERSO_RESIDUO_FORA_PONTA As Double
        Dim dTUSD As Double
        Dim dCONSUMO_MEDIDO As Double
        Dim dREVERSO_LIDO As Double

        Dim ddatast As Date
        Dim ddata_pagamento As Date

        Dim ldblTarPSeca As Double
        Dim ldblTarFPSeca As Double
        Dim ldblTarPUmida As Double
        Dim ldblTarFPUmida As Double
        '
        'Convencional
        'Quantidade
        Dim ldblQKwhCons As Double 'Qtde Consumo lido
        Dim ldblQKwhFat As Double 'Qtde Consumo faturado
        Dim ldblQKwhFatBan As Double 'Qtde Consumo faturado Bandeira
        Dim ldblQKwhFatTU As Double 'Qtde consumo faturado TUSD
        Dim ldblQkWhFatTE As Double 'Qtde consumo faturado TE
        Dim ldblQkWhFatTEBan As Double 'Qtde consumo faturado TE Bandeira
        'Dim ldblQKwhReverso As Double  'Qtde consumo reverso
        Dim ldblQKwContr As Double 'Qtde Demanda Contratada
        Dim ldblQKwFat As Double 'Qtde Demanda
        '
        Dim ldblVKwhCons As Double 'Valor Consumo lido
        Dim ldblVKwhFat As Double 'Valor Consumo faturado
        Dim ldblVKwhFatBan As Double 'Valor Consumo faturado Bandeira
        Dim ldblVkWhFatTU As Double 'Valor consumo faturado TUSD
        Dim ldblVkWhFatTE As Double 'Valor consumo faturado TE
        Dim ldblVkWhFatTEBan As Double 'Valor consumo faturado TE Bandeira
        'Dim ldblVKwhReverso As Double  'Valor consumo reverso
        Dim ldblVKwFat As Double 'Valor Demanda
        '
        'Horosazonal
        Dim ldblQKwhFatp As Double 'Qtde Consumo Faturado p
        Dim ldblQKwhFati As Double 'Qtde Consumo Faturado i
        Dim ldblQKwhFatfp As Double 'Qtde Consumo Faturado fp

        Dim ldblQKwhFatpAUX As Double 'Qtde Consumo Faturado p
        Dim ldblQKwhFatfpAUX As Double 'Qtde Consumo Faturado fp

        Dim ldblQKwhFatpBan As Double 'Qtde Consumo Faturado p Bandeira
        Dim ldblQKwhFatiBan As Double 'Qtde Consumo Faturado i Bandeira
        Dim ldblQKwhFatfpBan As Double 'Qtde Consumo Faturado fp Bandeira
        Dim ldblQKwhFatpLiv As Double 'Qtde Consumo Faturado p Livre
        Dim ldblQKwhFatfpLiv As Double 'Qtde Consumo Faturado fp Livre
        '
        Dim ldblQKwhDevp As Double 'Qtde Consumo Devolvido p
        Dim ldblQKwhDevfp As Double 'Qtde Consumo Devolvido fp
        Dim ldblQKwhUtrp As Double 'Qtde Consumo Ultrapassado p
        Dim ldblQKwhUtrfp As Double 'Qtde Consumo Ultrapassado fp
        '
        Dim ldblQKwContrp As Double 'Qtde Demanda Contratada Ponta
        Dim ldblQKwContrfp As Double 'Qtde Demanda Contratada Fora Ponta
        Dim ldblQKwFatp As Double 'Qtde Demanda p
        Dim ldblQKwFatfp As Double 'Qtde Demanda fp
        Dim ldblQKwDifFatp As Double 'Qtde Dif. Demanda p
        Dim ldblQKwDifFatfp As Double 'Qtde Dif. Demanda fp
        Dim ldblQKwFatUp As Double 'Qtde Demanda Ultrapassagem p
        Dim ldblQKwFatUfp As Double 'Qtde Demanda Ultrapassagem fp
        '
        Dim ldblVKwhFatp As Double 'Valor Consumo faturado p
        Dim ldblVKwhFati As Double 'Valor Consumo faturado i
        Dim ldblVKwhFatfp As Double 'Valor Consumo faturado fp
        Dim ldblVKwhFatpBan As Double 'Valor Consumo faturado p Badeira
        Dim ldblVKwhFatiBan As Double 'Valor Consumo faturado i Badeira
        Dim ldblVKwhFatfpBan As Double 'Valor Consumo faturado fp Bandeira
        Dim ldblVKwhFatpLiv As Double 'Valor Consumo faturado p Livre
        Dim ldblVKwhFatfpLiv As Double 'Valor Consumo faturado fp Livre
        '
        Dim ldblVKwhDevp As Double 'Valor Consumo devolvido p
        Dim ldblVKwhDevfp As Double 'Valor Consumo devolvido fp
        Dim ldblVKwhUtrp As Double 'Valor Consumo Ultrapassado p
        Dim ldblVKwhUtrfp As Double 'Valor Consumo Ultrapassado fp
        '
        Dim ldblVKwFatp As Double 'Valor Demanda p
        Dim ldblVKwFatfp As Double 'Valor Demanda fp
        Dim ldblVKwDifFatp As Double 'Valor Dif. Demanda p
        Dim ldblVKwDifFatfp As Double 'Valor Dif. Demanda fp
        Dim ldblVKwFatUp As Double 'Valor Demanda Ultrapassagem p
        Dim ldblVKwFatUfp As Double 'Valor Demanda Ultrapassagem fp

        'Micro Geração
        Dim ldblQKwhReversop As Double 'Qtde consumo reverso p
        Dim ldblQKwhReversoi As Double 'Qtde consumo reverso i
        Dim ldblQKwhReversofp As Double 'Qtde consumo reverso fp
        Dim ldblVKwhReversop As Double 'Valor consumo reverso p
        Dim ldblVKwhReversoi As Double 'Valor consumo reverso i
        Dim ldblVKwhReversofp As Double 'Valor consumo reverso fp

        Dim ldblVKwhReversoCompTEQtde As Double
        Dim ldblVKwhReversoCompTUSDQtde As Double

        Dim ldblVKwhReversoCompTEVlr As Double
        Dim ldblVKwhReversoCompTUSDVlr As Double

        Dim ldblQKwhReversop_sefaz As Double 'Qtde consumo reverso p
        Dim ldblQKwhReversoi_sefaz As Double 'Qtde consumo reverso i
        Dim ldblQKwhReversofp_sefaz As Double 'Qtde consumo reverso fp
        Dim ldblVKwhReversop_sefaz As Double 'Valor consumo reverso p
        Dim ldblVKwhReversoi_sefaz As Double 'Valor consumo reverso i
        Dim ldblVKwhReversofp_sefaz As Double 'Valor consumo reverso fp

        '
        'pela demanda
        Dim ldblVkwDscProv As Double 'Desconto provisorio
        Dim ldblVkwDscReal As Double 'Desconto real
        Dim ldblVkwDevCcee As Double 'Diferença a devolver
        Dim ldblVkwCobCcee As Double 'Diferença a cobrar
        '
        'pelo consumo
        Dim ldblVkwhDscProv As Double 'Desconto provisorio
        Dim ldblVkwhDscReal As Double 'Desconto real
        Dim ldblVkwhDevCcee As Double 'Diferença a devolver
        Dim ldblVkwhCobCcee As Double 'Diferença a cobrar
        '
        Dim ldblTip As Double 'Valor de iluminação publica.
        Dim ldblIcms1 As Double 'Valor de icms.
        Dim ldblIcms2 As Double 'Valor de icms.
        Dim ldblPis As Double 'Valor de PIS.
        Dim ldblCofins As Double 'Valor de COFINS.
        '
        Dim ldblIcmsSt As Double 'Icms Sistema Transmissão
        Dim ldblPisSt As Double 'Pis Sistema Transmissão
        Dim ldblCofinsSt As Double 'Cofns Sistema Transmissão
        '
        Dim ldblBaseIcms1 As Double 'valor da base ICMS.
        Dim ldblBaseIcms2 As Double 'valor da base ICMS.
        Dim ldblBasePis As Double 'Valor Base PIS.
        Dim ldblBaseCofins As Double 'Valor Base COFINS.
        '
        Dim ldblIcmsPisCof As Double 'valor de icms/pis/cofins.
        Dim ldblSaldoArre As Double
        Dim ldblEncFinan As Double
        '
        Dim dblAliquota As Double 'valor aliquota.
        Dim ldblIsentoIcms As Double 'valor Isento ICMS.
        Dim ldblDiferido As Double 'valor Diferido.
        Dim dblConReativReserv As Double 'valor consumo reativo reservado
        Dim ldblIcmsSobretaxa As Double 'icms sobre taxa
        '
        Dim ldblDifEltrbr As Double '
        Dim ldblJuros As Double 'juros verificar ainda com o calculo.
        Dim ldblEncargo As Double 'encargos confirma ainda com o calculo
        Dim ldblMust As Double
        '
        Dim ldblConsumoReativo As Double 'Consumo Reativo (Convencional)
        Dim ldblDemandaReativa As Double 'Demanda Reativo (Convencional)
        Dim ldblConsumoReativop As Double 'Consumo Reativo na ponta (Horosazonal)
        Dim ldblConsumoReativofp As Double 'Consumo Reativo fora da ponta (Horosazonal)
        Dim ldblDemandaReativap As Double 'Demanda Reativo na ponta (Horosazonal)
        Dim ldblDemandaReativafp As Double 'Demanda Reativo fora da ponta (Horosazonal)
        '
        Dim ldblDiversos As Double
        Dim ldblTaxados As Double
        Dim ldblConvenios As Double
        Dim ldblDevolucao As Double
        Dim ldblDevolucao_1 As Double
        Dim ldblRetencao As Double
        '
        Dim ldblAux As Double
        '
        Dim lstrSql As String
        Dim lstrSqlPri As String
        Dim lstrSqlPAx As String
        Dim lstrSqlIte As String
        Dim lstrSqlIAx As String
        Dim ldblDiferenca As Double

        Dim ldblDiferencaTot As Double


        Dim lintSequencia As Short

        Dim vlist

        Dim objNf As New entidadeNf
        Dim repositorioNf As New repositorioNf

        Dim objNfTransicao As New entidadeNfTransicao
        Dim repositorioNfTransicao As New repositorioNfTransicao

        Dim objTempEstatisItens As New entidadeTempEstatisItens
        Dim repositorioTempEstatisItens As New repositorioTempEstatisItens

        Dim objTempEstatis As New entidadeTempEstatis
        Dim repositorioTempEstatis As New repositorioTempEstatis

        Dim bPlan As Boolean = False

        Try

            iblnTar_A4 = False
            iblnTar_AA = False
            iblnTar_AL = False
            iblnTar_AS = False
            iblnTar_AV = False
            iblnTar_AX = False
            iblnTar_B = False

            'If chkPlanilha.Checked = True Then

            '    LinhaPlan = 1

            '    Dim misValue As Object = System.Reflection.Missing.Value
            '    ExcelAPP = New Microsoft.Office.Interop.Excel.Application
            '    ExcelPasta = ExcelAPP.Workbooks.Add(misValue)
            '    ExcelPlanilha = ExcelPasta.Worksheets.Add()
            '    ExcelPlanilha.Name = "Plan1"
            '    ExcelPlanilha.Activate()

            '    Me.lblInfo.Text = " Montando Planilha"
            '    Me.lblInfo.Refresh()

            '    If txtArq.Text = "" Then
            '        MessageBox.Show("Favor informar o local onde será salvo o .xls!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information)
            '        Exit Function
            '    End If

            '    sCabecalhoPlan()

            '    bPlan = True

            'End If

            lstrFilPref = GetFiltroPrefixo()

            If Me.chkTrans.CheckState = System.Windows.Forms.CheckState.Checked And Me.chkPreviaFat.CheckState = System.Windows.Forms.CheckState.Checked Then
                istrTabNf = "NF"
            ElseIf Me.chkTrans.CheckState = System.Windows.Forms.CheckState.Checked Then
                istrTabNf = "NFTRANSICAO"
            End If


            ldteFim = CDate(UltimoDiaMes(CShort(VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex)), CShort(Me.txtAno.Text)) & "/" & CShort(VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex)) & "/" & CShort(Me.txtAno.Text))
            ldteIni = CDate("01/" & VB6.Format(ldteFim, "MM/yyyy"))

            'ldteFim = "15/08/2023"
            ldteFimLeit = "15/08/2023"


            Dim lstrFiltro As String

            If istrTabNf = "NF" Then

                If Me.chkRen863_2019.CheckState = System.Windows.Forms.CheckState.Checked Then
                        lstrFiltro = lstrFiltro & " And ((NF.ANOMES_FAT >= '" & Me.txtAno.Text & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) & "'"
                        lstrFiltro = lstrFiltro & " AND  NF.ANOMES_FAT <= '" & Me.txtAno.Text & VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex) & "' )"
                    Else
                    lstrFiltro = lstrFiltro & " AND ( (NF.MESANO_REF >= '" & Me.txtAno.Text & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) & "'"
                        lstrFiltro = lstrFiltro & " AND NF.MESANO_REF <= '" & Me.txtAno.Text & VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex) & "' )"
                    End If

                lstrFiltro = lstrFiltro & " OR ( "
                        lstrFiltro = lstrFiltro & "   NF.FLGST = 'C' AND "
                        lstrFiltro = lstrFiltro & "   NF.MESANO_REF <> DATE_FORMAT(DATAST,'%Y%M') AND "
                        lstrFiltro = lstrFiltro & "   NF.DATAST >= DATE_FORMAT('" & CDate(ldteIni) & "','%Y%M%D') AND NF.DATAST <= DATE_FORMAT('" & CDate(ldteFim) & "','%Y%M%D') "
                        lstrFiltro = lstrFiltro & "  )"
                        lstrFiltro = lstrFiltro & " )"

                If lstrFilPref <> "" Then
                        lstrFiltro = lstrFiltro & " And NF.ROTA_QUATRO >= '" & Microsoft.VisualBasic.Left(lstrFilPref, 2) & Microsoft.VisualBasic.Right(VB6.GetItemString(Me.cmbRotaIni, Me.cmbRotaIni.SelectedIndex), 2) & "'"
                        lstrFiltro = lstrFiltro & " AND NF.ROTA_QUATRO <= '" & Microsoft.VisualBasic.Right(lstrFilPref, 2) & Microsoft.VisualBasic.Right(VB6.GetItemString(Me.cmbRotaFim, Me.cmbRotaFim.SelectedIndex), 2) & "'"
                    Else
                        lstrFiltro = lstrFiltro & " AND NF.CADERNO  >= '" & Convert.ToInt32(VB6.GetItemString(Me.cmbRotaIni, Me.cmbRotaIni.SelectedIndex)) & "'"
                        lstrFiltro = lstrFiltro & " AND NF.CADERNO  <= '" & Convert.ToInt32(VB6.GetItemString(Me.cmbRotaFim, Me.cmbRotaFim.SelectedIndex)) & "'"
                    End If

                    If Len(Trim(astrFiltro_Zona)) > 0 Then
                        objNf.ZONA = astrFiltro_Zona
                        lstrFiltro = lstrFiltro & " AND NF.ZONA in( " & astrFiltro_Zona & ")"
                    End If

                    'Filtra caso somente um grupo tenha sido checado
                    If Me.chkGrupoA.CheckState = System.Windows.Forms.CheckState.Checked And Not Me.chkGrupoB.CheckState = System.Windows.Forms.CheckState.Checked Then
                        objNf.GRUPO = "A"
                        lstrFiltro = lstrFiltro & " AND NF.GRUPO = 'A'"
                    ElseIf Me.chkGrupoB.CheckState = System.Windows.Forms.CheckState.Checked And Not Me.chkGrupoA.CheckState = System.Windows.Forms.CheckState.Checked Then
                        objNf.GRUPO = "B"
                        lstrFiltro = lstrFiltro & " AND NF.GRUPO = 'B'"
                    End If

                    If Me.chkSomenteMiicrogeradoras.CheckState = System.Windows.Forms.CheckState.Checked Then
                        objNf.MICRO_GERACAO = 1
                        objNf.MICRO_GERACAO_DISTRIBUIDA = 1
                        lstrFiltro = lstrFiltro & " AND (NF.MICRO_GERACAO = 1"
                        lstrFiltro = lstrFiltro & " OR NF.MICRO_GERACAO_DISTRIBUIDA = 1)"
                        If Me.opbSomenteMGSefaz.Checked Then
                            lstrFiltro = lstrFiltro & " AND NF.MICRO_GERACAO_CONVENIO_SEFAZ = 1"
                            objNf.MICRO_GERACAO_CONVENIO_SEFAZ = 1
                        ElseIf Me.opbSomenteMGNaoSefaz.Checked Then
                            lstrFiltro = lstrFiltro & " AND NF.MICRO_GERACAO_CONVENIO_SEFAZ = 0"
                            objNf.MICRO_GERACAO_CONVENIO_SEFAZ = 0
                        End If
                    End If

                    If Me.opbRegiaoUrbano.Checked Then
                        objNf.REGIAO = "U"
                        lstrFiltro = lstrFiltro & " AND NF.REGIAO = 'U'"
                    ElseIf Me.opbRegiaoRural.Checked Then
                        objNf.REGIAO = "R"
                        lstrFiltro = lstrFiltro & " AND NF.REGIAO = 'R'"
                    End If

                    If Me.chkFatComplementar.CheckState = System.Windows.Forms.CheckState.Checked Then
                        lstrFiltro = lstrFiltro & " AND NF.FATURA_COMPLEMENTAR > 0"
                        objNf.FATURA_COMPLEMENTAR = 1
                    Else
                        lstrFiltro = lstrFiltro & " AND NF.FATURA_COMPLEMENTAR = 0"
                        objNf.FATURA_COMPLEMENTAR = 0
                    End If

                    lstrFiltro = lstrFiltro & " AND NF.ITENSSERV IS NOT NULL"

                    If cmbTipo.SelectedIndex = 1 Then
                        lstrFiltro = lstrFiltro & " AND CONSUM.MATRICULA > 0"
                    ElseIf cmbTipo.SelectedIndex = 2 Then
                        lstrFiltro = lstrFiltro & " AND CONSUM.MATRICULA <= 0"
                    End If

                    lstrFiltro = lstrFiltro & MontaFiltroDataLeitura("NF")

                    'objExecAtualizaBancoDados.QUERY_NAME = fRetornaView(lstrFiltro, "NF")
                    objExecAtualizaBancoDados.QUERY_NAME = fRetornaView_Recebimentos(lstrFiltro, "NF", False)
                dt = repositorioAtualizaBancoDados.Consultar(objExecAtualizaBancoDados)

                Dim cont = 0
                If dt.Rows.Count > 0 Then

                    'If vlist.Count > 0 Then

                    BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 0, dt.Rows.Count)

                    If CriaTabelas(lstrSqlPri, lstrSqlIte, True, True, True) Then
                        lstrSqlIAx = ""
                        lstrSqlPAx = ""
                        lintContInsertPri = 1
                        lintContInsertItens = 1

                        'For Each objNfFor As entidadeNf In vlist
                        For Each row As DataRow In dt.Rows
                            cont += 1
                            If cont = 22 Then
                                Dim aix = "entrou"
                            End If
                            'Busca a matricula do socios caso seja nula ou em branco sempre sera ZERO
                            lblnControl = True

                            If llngMatricula = 1005 Then
                                llngMatricula = llngMatricula
                            End If

                            dvalor_juros_ece = Trim(IIf(IsDBNull(row.Item("valor_juros_ece")), 0, row.Item("valor_juros_ece")))
                            dvalor_ece = Trim(IIf(IsDBNull(row.Item("valor_ece")), 0, row.Item("valor_ece")))
                            dvalor_liquido = Trim(IIf(IsDBNull(row.Item("valor_liquido")), 0, row.Item("valor_liquido")))
                            dqtde_fx1 = Trim(IIf(IsDBNull(row.Item("qtde_fx1")), 0, row.Item("qtde_fx1")))
                            dqtde_fx2 = Trim(IIf(IsDBNull(row.Item("qtde_fx2")), 0, row.Item("qtde_fx2")))
                            dqtde_fx3 = Trim(IIf(IsDBNull(row.Item("qtde_fx3")), 0, row.Item("qtde_fx3")))
                            dqtde_fx4 = Trim(IIf(IsDBNull(row.Item("qtde_fx4")), 0, row.Item("qtde_fx4")))
                            dvlr_fx1 = Trim(IIf(IsDBNull(row.Item("vlr_fx1")), 0, row.Item("vlr_fx1")))
                            dvlr_fx2 = Trim(IIf(IsDBNull(row.Item("vlr_fx2")), 0, row.Item("vlr_fx2")))
                            dvlr_fx3 = Trim(IIf(IsDBNull(row.Item("vlr_fx3")), 0, row.Item("vlr_fx3")))
                            dvlr_fx4 = Trim(IIf(IsDBNull(row.Item("vlr_fx4")), 0, row.Item("vlr_fx4")))
                            dkwh_lido = Trim(IIf(IsDBNull(row.Item("kwh_lido")), 0, row.Item("kwh_lido")))
                            dbase_icms_1 = Trim(IIf(IsDBNull(row.Item("base_icms_1")), 0, row.Item("base_icms_1")))
                            daliquota_icms_1 = Trim(IIf(IsDBNull(row.Item("aliquota_icms_1")), 0, row.Item("aliquota_icms_1")))
                            dvalor_icms_1 = Trim(IIf(IsDBNull(row.Item("valor_icms_1")), 0, row.Item("valor_icms_1")))
                            dbase_icms_2 = Trim(IIf(IsDBNull(row.Item("base_icms_2")), 0, row.Item("base_icms_2")))
                            daliquota_icms_2 = Trim(IIf(IsDBNull(row.Item("aliquota_icms_2")), 0, row.Item("aliquota_icms_2")))
                            dvalor_icms_2 = Trim(IIf(IsDBNull(row.Item("valor_icms_2")), 0, row.Item("valor_icms_2")))
                            dAliquota_PIS = Trim(IIf(IsDBNull(row.Item("Aliquota_PIS")), 0, row.Item("Aliquota_PIS")))
                            dAliquota_COFINS = Trim(IIf(IsDBNull(row.Item("Aliquota_COFINS")), 0, row.Item("Aliquota_COFINS")))
                            dreceitas_financeiras = Trim(IIf(IsDBNull(row.Item("receitas_financeiras")), 0, row.Item("receitas_financeiras")))
                            dressarcimento_idqual = Trim(IIf(IsDBNull(row.Item("ressarcimento_idqual")), 0, row.Item("ressarcimento_idqual")))
                            dvalor_encargo_uso_sis_trans = Trim(IIf(IsDBNull(row.Item("valor_encargo_uso_sis_trans")), 0, row.Item("valor_encargo_uso_sis_trans")))
                            ddesconto_must = Trim(IIf(IsDBNull(row.Item("desconto_must")), 0, row.Item("desconto_must")))
                            dencargo_kwh_faturado_ponta = Trim(IIf(IsDBNull(row.Item("encargo_kwh_faturado_ponta")), 0, row.Item("encargo_kwh_faturado_ponta")))
                            dencargo_valor_kwh_faturado_ponta = Trim(IIf(IsDBNull(row.Item("encargo_valor_kwh_faturado_ponta")), 0, row.Item("encargo_valor_kwh_faturado_ponta")))
                            dencargo_kwh_faturado_fora_ponta = Trim(IIf(IsDBNull(row.Item("encargo_kwh_faturado_fora_ponta")), 0, row.Item("encargo_kwh_faturado_fora_ponta")))
                            dencargo_valor_kwh_faturado_fora_ponta = Trim(IIf(IsDBNull(row.Item("encargo_valor_kwh_faturado_fora_ponta")), 0, row.Item("encargo_valor_kwh_faturado_fora_ponta")))
                            dmwh_medio = Trim(IIf(IsDBNull(row.Item("mwh_medio")), 0, row.Item("mwh_medio")))
                            dmwh_medio_horas = Trim(IIf(IsDBNull(row.Item("mwh_medio_horas")), 0, row.Item("mwh_medio_horas")))
                            dVALOR_REVERSO = Trim(IIf(IsDBNull(row.Item("VALOR REVERSO")), 0, row.Item("VALOR REVERSO")))
                            dVALOR_REVERSO_BAN = Trim(IIf(IsDBNull(row.Item("VALOR REVERSO BAN")), 0, row.Item("VALOR REVERSO BAN")))
                            dREVERSO_PONTA = Trim(IIf(IsDBNull(row.Item("REVERSO PONTA")), 0, row.Item("REVERSO PONTA")))
                            dREVERSO_PONTA_BANDEIRA = Trim(IIf(IsDBNull(row.Item("REVERSO PONTA BANDEIRA")), 0, row.Item("REVERSO PONTA BANDEIRA")))
                            dREVERSO_FORA_DE_PONTA = Trim(IIf(IsDBNull(row.Item("REVERSO FORA DE PONTA")), 0, row.Item("REVERSO FORA DE PONTA")))
                            dREVERSO_FORA_DE_PONTA_BANDEIRA = Trim(IIf(IsDBNull(row.Item("REVERSO FORA DE PONTA BANDEIRA")), 0, row.Item("REVERSO FORA DE PONTA BANDEIRA")))
                            dbandeira_vlr_kwh_fat = Trim(IIf(IsDBNull(row.Item("bandeira_vlr_kwh_fat")), 0, row.Item("bandeira_vlr_kwh_fat")))
                            dbandeira_valor_kwh_fat_ponta = Trim(IIf(IsDBNull(row.Item("bandeira_valor_kwh_fat_ponta")), 0, row.Item("bandeira_valor_kwh_fat_ponta")))
                            dbandeira_valor_kwh_fat_fora_ponta = Trim(IIf(IsDBNull(row.Item("bandeira_valor_kwh_fat_fora_ponta")), 0, row.Item("bandeira_valor_kwh_fat_fora_ponta")))
                            dvalor_energia_desconto_provisorio = Trim(IIf(IsDBNull(row.Item("valor_energia_desconto_provisorio")), 0, row.Item("valor_energia_desconto_provisorio")))
                            dvalor_energia_desconto_realizado = Trim(IIf(IsDBNull(row.Item("valor_energia_desconto_realizado")), 0, row.Item("valor_energia_desconto_realizado")))
                            dvalor_energia_devolucao_diferenca_ccee = Trim(IIf(IsDBNull(row.Item("valor_energia_devolucao_diferenca_ccee")), 0, row.Item("valor_energia_devolucao_diferenca_ccee")))
                            dvalor_energia_cobranca_diferenca_ccee = Trim(IIf(IsDBNull(row.Item("valor_energia_cobranca_diferenca_ccee")), 0, row.Item("valor_energia_cobranca_diferenca_ccee")))
                            dCONSUMO_PONTA = Trim(IIf(IsDBNull(row.Item("CONSUMO_PONTA")), 0, row.Item("CONSUMO_PONTA")))
                            dCONSUMO_FORA_PONTA = Trim(IIf(IsDBNull(row.Item("CONSUMO_FORA_PONTA")), 0, row.Item("CONSUMO_FORA_PONTA")))
                            dREVERSO_FORA_PONTA = Trim(IIf(IsDBNull(row.Item("REVERSO_FORA_PONTA")), 0, row.Item("REVERSO_FORA_PONTA")))
                            dREVERSO_RESIDUO_FORA_PONTA = Trim(IIf(IsDBNull(row.Item("REVERSO_RESIDUO_FORA_PONTA")), 0, row.Item("REVERSO_RESIDUO_FORA_PONTA")))
                            dTUSD = Trim(IIf(IsDBNull(row.Item("TUSD")), 0, row.Item("TUSD")))
                            dCONSUMO_MEDIDO = Trim(IIf(IsDBNull(row.Item("CONSUMO_MEDIDO")), 0, row.Item("CONSUMO_MEDIDO")))
                            dREVERSO_LIDO = Trim(IIf(IsDBNull(row.Item("REVERSO_LIDO")), 0, row.Item("REVERSO_LIDO")))
                            ddatast = Trim(IIf(IsDBNull(row.Item("datast")), "1900-01-01", row.Item("datast")))
                            ddata_pagamento = Trim(IIf(IsDBNull(row.Item("data_pagamento")), "1900-01-01", row.Item("data_pagamento")))

                            sGrupo_tarifario = Trim(IIf(IsDBNull(row.Item("grupo_tarifario")), "", row.Item("grupo_tarifario")))
                            sClasse_faturada = Trim(IIf(IsDBNull(row.Item("classe_faturada")), "", row.Item("classe_faturada")))
                            sDescricao_classe = "" 'Trim(IIf(IsDBNull(row.Item("descricao_classe")), "", row.Item("descricao_classe")))
                            sMesano_referencia = Trim(IIf(IsDBNull(row.Item("mesano_referencia")), "", row.Item("mesano_referencia")))
                            sAnomes_fat = Trim(IIf(IsDBNull(row.Item("anomes_fat")), "", row.Item("anomes_fat")))
                            dData_vencimento = CDate(Trim(IIf(IsDBNull(row.Item("data_vencimento")), "1900-01-01", row.Item("data_vencimento"))))
                            dData_leitura_atual = CDate(Trim(IIf(IsDBNull(row.Item("data_leitura_atual")), "1900-01-01", row.Item("data_leitura_atual"))))
                            dData_leitura_anterior = CDate(Trim(IIf(IsDBNull(row.Item("data_leitura_anterior")), "1900-01-01", row.Item("data_leitura_anterior"))))
                            dNumNf = CInt(IIf(IsDBNull(row.Item("numero_fatura")), 0, row.Item("numero_fatura")))
                            llngMatricula = CInt(IIf(IsDBNull(row.Item("MATRICULA")), 0, row.Item("MATRICULA")))
                            lstrFlgSt = Trim(IIf(IsDBNull(row.Item("FLGST")), "", row.Item("FLGST")))
                            ldteFlgSt = CDate(IIf(IsDBNull(row.Item("DATAST")), "1900-01-01", row.Item("DATAST")))
                            lstrMesAno = IIf(IsDBNull(row.Item("MESANO")), "01/1900", row.Item("MESANO"))

                            ldteEmissao = CDate(IIf(IsDBNull(row.Item("data_emissao")), "1900-01-01", row.Item("data_emissao")))
                            ldteApresentacao = CDate(IIf(IsDBNull(row.Item("data_apresentacao")), "1900-01-01", row.Item("data_apresentacao")))

                            'If lstrFlgSt = "C" Then
                            '    If ldteFlgSt >= CDate("01/" & lstrMesAno) And ldteFlgSt <= CDate(UltimoDiaMes(Microsoft.VisualBasic.Left(lstrMesAno, 2), Microsoft.VisualBasic.Right(lstrMesAno, 4)) & "/" & lstrMesAno) Then
                            '        lblnControl = False
                            '    Else
                            '        lblnControl = True
                            '    End If

                            'End If

                            If istrSocios = "1" Then
                                If Me.cmbSocios.SelectedIndex = 1 Then 'Somente Socios
                                    lblnControl = (llngMatricula > 0)
                                ElseIf Me.cmbSocios.SelectedIndex = 2 Then  'Somente não socios
                                    lblnControl = (llngMatricula = 0)
                                End If
                            End If

                            If lblnControl = True Then

                                lstrItens = IIf(IsDBNull(row.Item("ITENSSERV")), "", row.Item("ITENSSERV"))
                                lstrClasse = IIf(IsDBNull(row.Item("codigo_classe")), "0000", row.Item("codigo_classe"))
                                lstrZona = IIf(IsDBNull(row.Item("ZONA")), "000", row.Item("ZONA"))
                                lstrLivro = IIf(IsDBNull(row.Item("LIVRO")), "00", row.Item("LIVRO"))
                                lstrConta = IIf(IsDBNull(row.Item("CONTA")), "000000", row.Item("CONTA"))
                                llngUnidId = CInt(IIf(IsDBNull(row.Item("UNID_ID")), 0, row.Item("UNID_ID")))
                                llngConsId = CInt(IIf(IsDBNull(row.Item("CONS_ID")), 0, row.Item("CONS_ID")))
                                lstrGrupo = Mid(IIf(IsDBNull(row.Item("TA")), "01B1", row.Item("TA")), 3, 2)
                                lstrNome = BuscaNome(llngConsId, llngUnidId, Microsoft.VisualBasic.Left(lstrGrupo, 1))
                                lintLivreEspecial = IIf(IsDBNull(row.Item("LIVREESPECIAL")), 0, row.Item("LIVREESPECIAL"))
                                lintLivreVerde = IIf(IsDBNull(row.Item("LIVRE_VERDE")), 0, row.Item("LIVRE_VERDE"))
                                lintParcialmenteCativo = IIf(IsDBNull(row.Item("PARCIALMENTE_CATIVO")), 0, row.Item("PARCIALMENTE_CATIVO"))
                                lstrFase = IIf(IsDBNull(row.Item("FASE")), "M", row.Item("FASE"))
                                lstrFlgSt = Trim(IIf(IsDBNull(row.Item("FLGST")), "", row.Item("FLGST")))
                                ldteFlgSt = CDate(IIf(IsDBNull(row.Item("DATAST")), "1900-01-01", row.Item("DATAST")))
                                lstrFlgMedFat = Trim(IIf(IsDBNull(row.Item("FLGMEDFAT")), "", row.Item("FLGMEDFAT")))

                                Dim bFATURA_FINAL As Boolean = Trim(IIf(IsDBNull(row.Item("FATURA_FINAL")), 0, row.Item("FATURA_FINAL")))
                                lintFaturaFinal = IIf(bFATURA_FINAL, 1, 0)

                                Dim bIRRIGACAO_AQUICULTURA As Boolean = Trim(IIf(IsDBNull(row.Item("IRRIGACAO_AQUICULTURA")), 0, row.Item("IRRIGACAO_AQUICULTURA")))
                                lintIrrigacaoAquicultura = IIf(bIRRIGACAO_AQUICULTURA, 1, 0)

                                Dim bMICRO_GERACAO_CONVENIO_SEFAZ As Boolean = Trim(IIf(IsDBNull(row.Item("MICRO_GERACAO_CONVENIO_SEFAZ")), 0, row.Item("MICRO_GERACAO_CONVENIO_SEFAZ")))
                                lintFaturaFinal = IIf(bFATURA_FINAL, 1, 0)

                                Dim bMICRO_GERACAO As Boolean = Trim(IIf(IsDBNull(row.Item("MICRO_GERACAO")), 0, row.Item("MICRO_GERACAO")))
                                lintMicroGeracao = IIf(bMICRO_GERACAO, 1, 0)

                                Dim bMICRO_GERACAO_DISTRIBUIDA As Boolean = Trim(IIf(IsDBNull(row.Item("MICRO_GERACAO_DISTRIBUIDA")), 0, row.Item("MICRO_GERACAO_DISTRIBUIDA")))
                                lintMicroGeracaoDistribuida = IIf(bMICRO_GERACAO_DISTRIBUIDA, 1, 0)

                                Dim bTARIFA_BRANCA As Boolean = Trim(IIf(IsDBNull(row.Item("TARIFA_BRANCA")), 0, row.Item("TARIFA_BRANCA")))
                                lintTarifaBranca = IIf(bTARIFA_BRANCA, 1, 0)

                                'If lstrFlgSt = "C" Then
                                '    If ldteFlgSt <= ldteFim Then
                                '        lintMpr = -1
                                '    Else
                                '        lintMpr = 1
                                '    End If
                                'Else
                                lintMpr = 1
                                'End If

                                ldblValorTot = IIf(IsDBNull(row.Item("valor_total")), 0, row.Item("valor_total")) * lintMpr
                                lstrGrupoT = Microsoft.VisualBasic.Left(lstrGrupo, IIf(Microsoft.VisualBasic.Left(lstrGrupo, 1) = "B", 1, 2))

                                If lstrGrupoT = "A4" Then
                                    lstrGrupoT = "B"
                                End If

                                '
                                If lstrGrupo = "A4" Then iblnTar_A4 = True
                                If lstrGrupo = "AA" Then iblnTar_AA = True
                                If lstrGrupo = "AL" Then iblnTar_AL = True
                                If lstrGrupo = "AS" Then iblnTar_AS = True
                                If lstrGrupo = "AV" Then iblnTar_AV = True
                                If lstrGrupo = "AX" Then iblnTar_AX = True
                                If iblnTar_B = False And Microsoft.VisualBasic.Left(lstrGrupo, 1) = "B" Then iblnTar_B = True
                                '

                                'Convencional
                                'Quantidade
                                ldblQKwhCons = 0 'Consumo lido
                                ldblQKwhFat = 0 'Consumo faturado
                                ldblQKwhFatBan = 0 'Consumo Faturado Bandeira
                                ldblVKwhFatBan = 0 'Consumo faturado bandeira
                                ldblQKwhFatTU = 0 'Consumo faturado TUSD
                                ldblQkWhFatTE = 0 'Consumo faturado TE
                                ldblQkWhFatTEBan = 0 'Consumo faturado TE bandeira
                                'ldblQKwhReverso = 0  'Consumo reverso
                                ldblQKwContr = 0 'Demanda Contratada
                                ldblQKwFat = 0 'Demanda

                                'Valor
                                ldblVKwhCons = 0 'Consumo lido
                                ldblVKwhFat = 0 'Consumo faturado
                                ldblVKwhFatBan = 0 'Consumo faturado Bandeira
                                ldblVkWhFatTU = 0 'Consumo faturado TUSD
                                ldblVkWhFatTE = 0 'Consumo faturado TE
                                ldblVkWhFatTEBan = 0 'Consumo faturado TE bandeira
                                'ldblVKwhReverso = 0  'Consumo reverso
                                ldblVKwFat = 0 'Demanda
                                '

                                'Horosazonal
                                'Quantidade
                                ldblQKwhFatp = 0 'Qtde Consumo faturado p
                                ldblQKwhFati = 0 'Qtde Consumo faturado i
                                ldblQKwhFatfp = 0 'Qtde Consumo faturado fp
                                ldblQKwhFatpBan = 0 'Qtde Consumo faturado p Bandeira
                                ldblQKwhFatiBan = 0 'Qtde Consumo faturado i Bandeira
                                ldblQKwhFatfpBan = 0 'Qtde Consumo faturado fp Bandeira
                                ldblQKwhFatpLiv = 0 'Qtde Consumo faturado p Livre
                                ldblQKwhFatfpLiv = 0 'Qtde Consumo faturado fp Livre						
                                '
                                ldblQKwhDevp = 0 'Qtde Consumo Devolvido p
                                ldblQKwhDevfp = 0 'Qtde Consumo Devolvido fp
                                ldblQKwhUtrp = 0 'Qtde Consumo Ultrapassado p
                                ldblQKwhUtrfp = 0 'Qtde Consumo Ultrapassado fp
                                '							
                                ldblQKwContrp = 0 'Qtde Demanda Contratada p
                                ldblQKwContrfp = 0 'Qtde Demanda Contratada fp
                                ldblQKwFatp = 0 'Qtde Demanda p
                                ldblQKwFatfp = 0 'Qtde Demanda fp
                                ldblQKwDifFatp = 0 'Qtde Dif. Demanda p
                                ldblQKwDifFatfp = 0 'Qtde Dif. Demanda fp
                                ldblQKwFatUp = 0 'Qtde Demanda de ultrapassagem p
                                ldblQKwFatUfp = 0 'Qtde Demanda de ultrapassagem fp
                                ldblQKwhReversop = 0 'Qtde consumo reverso p
                                ldblQKwhReversoi = 0 'Qtde consumo reverso i
                                ldblQKwhReversofp = 0 'Qtde consumo reverso fp
                                ldblQKwhReversop_sefaz = 0 'Qtde consumo reverso p
                                ldblQKwhReversoi_sefaz = 0 'Qtde consumo reverso i
                                ldblQKwhReversofp_sefaz = 0 'Qtde consumo reverso fp

                                'Valor
                                ldblVKwhFatp = 0 'Valor Consumo faturado p
                                ldblVKwhFati = 0 'Valor Consumo faturado i
                                ldblVKwhFatfp = 0 'Valor Consumo faturado fp
                                ldblVKwhFatpBan = 0 'Valor Consumo faturado p Bandeira
                                ldblVKwhFatiBan = 0 'Valor Consumo faturado i Bandeira
                                ldblVKwhFatfpBan = 0 'Valor Consumo faturado fp Bandeira
                                ldblVKwhFatpLiv = 0 'Valor Consumo faturado p Livre
                                ldblVKwhFatfpLiv = 0 'Valor Consumo faturado fp Livre
                                '
                                ldblVKwhDevp = 0 'Valor Consumo devolvido p
                                ldblVKwhDevfp = 0 'Valor Consumo devolvido fp
                                ldblVKwhUtrp = 0 'Valor Consumo Ultrapassado p
                                ldblVKwhUtrfp = 0 'Valor Consumo Ultrapassado fp
                                '
                                ldblVKwFatp = 0 'Valor Demanda p
                                ldblVKwFatfp = 0 'Valor Demanda fp
                                ldblVKwDifFatp = 0 'Valor Dif. Demanda p
                                ldblVKwDifFatfp = 0 'Valor Dif. Demanda fp
                                ldblVKwFatUp = 0 'Valor Demanda de ultrapassagem p
                                ldblVKwFatUfp = 0 'Valor Demanda de ultrapassagem fp
                                '
                                ldblVKwhReversop = 0 'valor consumo reverso p
                                ldblVKwhReversoi = 0 'valor consumo reverso i
                                ldblVKwhReversofp = 0 'valor consumo reverso fp

                                ldblVKwhReversoCompTEQtde = 0
                                ldblVKwhReversoCompTUSDQtde = 0

                                ldblVKwhReversoCompTEVlr = 0
                                ldblVKwhReversoCompTUSDVlr = 0

                                ldblVKwhReversop_sefaz = 0 'valor consumo reverso p
                                ldblVKwhReversoi_sefaz = 0 'valor consumo reverso i
                                ldblVKwhReversofp_sefaz = 0 'valor consumo reverso fp

                                'Desconto Provisorio
                                ldblVkwDscProv = 0 'Desconto provisorio
                                ldblVkwDscReal = 0 'Desconto real
                                ldblVkwDevCcee = 0 'Diferença a devolver
                                ldblVkwCobCcee = 0 'Diferença a cobrar			
                                '
                                ldblVkwhDscProv = 0 'Desconto provisorio
                                ldblVkwhDscReal = 0 'Desconto real
                                ldblVkwhDevCcee = 0 'Diferença a devolver
                                ldblVkwhCobCcee = 0 'Diferença a cobrar
                                '----
                                ldblTip = 0 'Vlr Iluminação Pública.
                                ldblIcms1 = 0 'Vlr Icms.
                                ldblIcms2 = 0 'Vlr Icms.
                                ldblPis = 0 'Vlr PIS.
                                ldblCofins = 0 'Vlr COFINS.
                                '
                                ldblIcmsSt = 0 'Vlr Icms Substituição Tributária
                                ldblPisSt = 0 'Vlr Pis Substituição Tributária
                                ldblCofinsSt = 0 'Vlr Cofins Substituição Tributária
                                '			
                                ldblBaseIcms1 = 0 'Vlr Base Icms.
                                ldblBaseIcms2 = 0 'Vlr Base Icms.
                                ldblBasePis = 0 'Vlr Base PIS.
                                ldblBaseCofins = 0 'Vlr Base COFINS.					
                                '
                                ldblIcmsPisCof = 0 'Vlr Icms/Pis/Cofins.
                                ldblSaldoArre = 0
                                ldblEncFinan = 0
                                ldblDifEltrbr = 0
                                ldblJuros = 0 'Juros verificar ainda com o calculo.
                                ldblEncargo = 0 'Encargos confirma ainda com o calculo
                                ldblMust = 0 'Valor de MUST
                                '	
                                ldblConsumoReativo = 0 'Consumo Reativo
                                ldblDemandaReativa = 0 'Demanda Reativo
                                ldblConsumoReativop = 0 'Consumo Reativo p
                                ldblConsumoReativofp = 0 'Consumo Reativo fp
                                ldblDemandaReativap = 0 'Demanda Reativo p
                                ldblDemandaReativafp = 0 'Demanda Reativo fp

                                ldblDiferenca = 0
                                'ldblDiferencaTot = 0
                                '************

                                ldblBaseIcms1 = IIf(IsDBNull(row.Item("base_icms_1")), 0, row.Item("base_icms_1")) * lintMpr
                                'ldblBaseIcms1 = ldblBaseIcms1 + BuscaVlrItem(lstrItens, "0302063035") * lintMpr 'Marreta por problemas de calculo na fatura 21 de 12/2019
                                ldblBaseIcms2 = IIf(IsDBNull(row.Item("base_icms_2")), 0, row.Item("base_icms_2")) * lintMpr
                                ldblBasePis = IIf(IsDBNull(row.Item("base_pis")), 0, row.Item("base_pis")) * lintMpr
                                ldblBaseCofins = IIf(IsDBNull(row.Item("base_cofins")), 0, row.Item("base_cofins")) * lintMpr
                                ldblDiferenca = IIf(IsDBNull(row.Item("dif.rel.rec")), 0, row.Item("dif.rel.rec"))

                                If lstrGrupo = "AS" Or lstrGrupo = "A4" Or Microsoft.VisualBasic.Left(lstrGrupo, 1) = "B" Then

                                    If Microsoft.VisualBasic.Left(lstrGrupo, 1) <> "B" Then

                                        ldblQKwhCons = IIf(IsDBNull(row.Item("valor_total")), 0, row.Item("valor_total")) * lintMpr 'Consumo lido
                                        ldblQKwhFat = IIf(IsDBNull(row.Item("kwh_faturado")), 0, row.Item("kwh_faturado")) * lintMpr 'Consumo faturado
                                        'ldblQKwhFatBan = IIf(IsDBNull(row.Item("base_cofins")), 0, row.Item("base_cofins")) * lintMpr 'Consumo faturado bandeira ***

                                        ldblVKwhCons = IIf(IsDBNull(row.Item("vlr_kwh_faturado")), 0, row.Item("vlr_kwh_faturado")) * lintMpr 'Consumo lido ***
                                        ldblVKwhFat = IIf(IsDBNull(row.Item("vlr_kwh_faturado")), 0, row.Item("vlr_kwh_faturado")) * lintMpr 'Consumo faturado
                                        ldblVKwhFatBan = IIf(IsDBNull(row.Item("bandeira_vlr_kwh_fat")), 0, row.Item("bandeira_vlr_kwh_fat")) * lintMpr 'Consumo faturado bandeira

                                    Else

                                        'Quantidade
                                        ldblQKwhCons = IIf(IsDBNull(row.Item("valor_total")), 0, row.Item("valor_total")) * lintMpr 'Consumo lido

                                        If lintTarifaBranca = 0 Then
                                            ldblQKwhFat = IIf(IsDBNull(row.Item("kwh_faturado")), 0, row.Item("kwh_faturado")) * lintMpr 'Consumo faturado kwh_faturado
                                            'ldblQKwhFatBan = IIf(IsDBNull(row.Item("kwh_lido")), 0, row.Item("kwh_lido")) * lintMpr 'Consumo faturado bandeira ***
                                        Else
                                            ldblQKwhFatp = IIf(IsDBNull(row.Item("kwh_faturado")), 0, row.Item("kwh_faturado")) * lintMpr 'Consumo faturado
                                        End If

                                        ldblQKwhFatTU = IIf(IsDBNull(row.Item("TUSD")), 0, row.Item("TUSD")) * lintMpr 'consumo faturado TUSD
                                        'ldblQkWhFatTE = BuscaVlrItem(lstrItens, "030401009") * lintMpr 'consumo faturado TE
                                        'ldblQkWhFatTEBan = BuscaVlrItem(lstrItens, "030411009") * lintMpr 'consumo faturado TE bandeira

                                        'Valor
                                        'ldblVKwhCons = (BuscaVlrItem(lstrItens, "030202008") + BuscaVlrItem(lstrItens, "030202018") + BuscaVlrItem(lstrItens, "030202028") + BuscaVlrItem(lstrItens, "030202038")) * lintMpr 'Consumo lido
                                        ldblVKwhCons = IIf(IsDBNull(row.Item("vlr_kwh_faturado")), 0, row.Item("vlr_kwh_faturado")) * lintMpr

                                        If lintTarifaBranca = 0 Then
                                            'ldblVKwhFat = (BuscaVlrItem(lstrItens, "030202009")) * lintMpr 'Consumo faturado ***
                                            'ldblVKwhFatBan = (BuscaVlrItem(lstrItens, "030212009")) * lintMpr 'Consumo faturado bandeira ***

                                            ldblVKwhFat = IIf(IsDBNull(row.Item("vlr_kwh_faturado")), 0, row.Item("vlr_kwh_faturado")) * lintMpr 'Consumo faturado
                                            'ldblVKwhFatBan = (BuscaVlrItem(lstrItens, "030212009")) * lintMpr 'Consumo faturado bandeira ***
                                        Else

                                            'ldblVKwhFatp = (BuscaVlrItem(lstrItens, "030202019")) * lintMpr     'Consumo faturado ** *
                                            'ldblVKwhFati = (BuscaVlrItem(lstrItens, "030202029")) * lintMpr     'Consumo faturado ***
                                            'ldblVKwhFatfp = (BuscaVlrItem(lstrItens, "030202039")) * lintMpr    'Consumo faturado ***
                                            'ldblVKwhFatpBan = (BuscaVlrItem(lstrItens, "030212019")) * lintMpr  'Consumo faturado bandeira ***
                                            'ldblVKwhFatiBan = (BuscaVlrItem(lstrItens, "030212029")) * lintMpr  'Consumo faturado bandeira ***
                                            'ldblVKwhFatfpBan = (BuscaVlrItem(lstrItens, "030212039")) * lintMpr 'Consumo faturado bandeira ***

                                        End If

                                        If lintMicroGeracao = 1 Or lintMicroGeracaoDistribuida = 1 Then

                                            If lintMicroGeracaoConvenioSefaz = 0 Then

                                                ldblVKwhReversoCompTEQtde = IIf(IsDBNull(row.Item("qtd_COMP. TE")), 0, row.Item("qtd_COMP. TE"))
                                                ldblVKwhReversoCompTUSDQtde = IIf(IsDBNull(row.Item("qtd_COMP. TUSD")), 0, row.Item("qtd_COMP. TUSD"))

                                                ldblVKwhReversoCompTEVlr = IIf(IsDBNull(row.Item("vlr_COMP. TE")), 0, row.Item("vlr_COMP. TE"))
                                                ldblVKwhReversoCompTUSDVlr = IIf(IsDBNull(row.Item("vlr_COMP. TUSD")), 0, row.Item("vlr_COMP. TUSD"))

                                                ldblQKwhReversop = (ldblVKwhReversoCompTEQtde + ldblVKwhReversoCompTUSDQtde) * lintMpr
                                                ldblVKwhReversop = (ldblVKwhReversoCompTEVlr + ldblVKwhReversoCompTUSDVlr) * lintMpr

                                                ldblQKwhFat = ldblQKwhFat + ldblQKwhReversop
                                                ldblVKwhFat = ldblVKwhFat + ldblVKwhReversop

                                                ldblQKwhReversoi = 0 'implementar na rotina de calculo
                                                'ldblVKwhReversofp = IIf(IsDBNull(row.Item("VALOR REVERSO")), 0, row.Item("VALOR REVERSO")) * lintMpr
                                                ldblVKwhReversofp = IIf(IsDBNull(row.Item("REVERSO FORA DE PONTA")), 0, row.Item("REVERSO FORA DE PONTA")) * lintMpr 'Valor Reverso ***

                                            Else

                                                ldblVKwhReversoCompTEQtde = IIf(IsDBNull(row.Item("qtd_COMP. TE")), 0, row.Item("qtd_COMP. TE"))
                                                ldblVKwhReversoCompTUSDQtde = IIf(IsDBNull(row.Item("qtd_COMP. TUSD")), 0, row.Item("qtd_COMP. TUSD"))

                                                ldblVKwhReversoCompTEVlr = IIf(IsDBNull(row.Item("vlr_COMP. TE")), 0, row.Item("vlr_COMP. TE"))
                                                ldblVKwhReversoCompTUSDVlr = IIf(IsDBNull(row.Item("vlr_COMP. TUSD")), 0, row.Item("vlr_COMP. TUSD"))

                                                'ldblQKwhReversop_sefaz = (ldblVKwhReversoCompTEQtde + ldblVKwhReversoCompTUSDQtde) * lintMpr
                                                'ldblQKwhReversoi_sefaz = (ldblVKwhReversoCompTEVlr + ldblVKwhReversoCompTUSDVlr) * lintMpr

                                                ldblQKwhFat = ldblQKwhFat + ldblQKwhReversop
                                                ldblVKwhFat = ldblVKwhFat + ldblVKwhReversop

                                                'ldblVKwhReversofp_sefaz = IIf(IsDBNull(row.Item("VALOR REVERSO")), 0, row.Item("VALOR REVERSO")) * lintMpr 'Valor Reverso
                                                ldblVKwhReversofp_sefaz = IIf(IsDBNull(row.Item("REVERSO FORA DE PONTA")), 0, row.Item("REVERSO FORA DE PONTA")) * lintMpr 'Valor Reverso

                                            End If

                                        End If

                                        If lintMicroGeracaoConvenioSefaz = 0 Then

                                            If ldblVKwhReversofp = 0 Then
                                                If ldblVkWhFatTU + ldblVkWhFatTE > 0 Then
                                                    ldblVKwhReversofp = (ldblVKwhFat - (ldblVkWhFatTU + ldblVkWhFatTE)) * lintMpr 'Valor Reverso
                                                    If ldblVKwhFat - (ldblVkWhFatTU + ldblVkWhFatTE) > 0 Then
                                                        ldblVKwhReversofp = ldblVKwhReversofp + (ldblVKwhFatBan - ldblVkWhFatTEBan)
                                                    End If
                                                End If
                                            End If

                                        Else

                                            If ldblVKwhReversofp_sefaz = 0 Then
                                                If ldblVkWhFatTU + ldblVkWhFatTE > 0 Then
                                                    ldblVKwhReversofp_sefaz = (ldblVKwhFat - (ldblVkWhFatTU + ldblVkWhFatTE)) * lintMpr 'Valor Reverso
                                                    If ldblVKwhFat - (ldblVkWhFatTU + ldblVkWhFatTE) > 0 Then
                                                        ldblVKwhReversofp_sefaz = ldblVKwhReversofp_sefaz + (ldblVKwhFatBan - ldblVkWhFatTEBan)
                                                    End If
                                                End If
                                            End If

                                        End If

                                    End If

                                    If ldblDiferenca <> 0 Then
                                        ldblVKwhReversop = ldblVKwhReversop + ldblDiferenca '(ldblDiferenca * -1)
                                        ldblDiferencaTot = ldblDiferencaTot + ldblDiferenca
                                    End If

                                    'Demanda
                                    ldblQKwContr = IIf(IsDBNull(row.Item("demanda_contratada_convencional")), 0, row.Item("demanda_contratada_convencional")) * lintMpr 'Demanda Contratada
                                    ldblQKwFat = IIf(IsDBNull(row.Item("kw_faturado")), 0, row.Item("kw_faturado")) * lintMpr 'Demanda
                                    ldblQKwFatUfp = IIf(IsDBNull(row.Item("kw_ultrapassado")), 0, row.Item("kw_ultrapassado")) * lintMpr 'Demanda de ultrapassagem fp

                                    'Valor
                                    ldblVKwFat = IIf(IsDBNull(row.Item("valor_kw_faturado")), 0, row.Item("valor_kw_faturado")) * lintMpr 'Demanda
                                    ldblVKwFatUfp = IIf(IsDBNull(row.Item("valor_kw_ultrapassado")), 0, row.Item("valor_kw_ultrapassado")) * lintMpr 'Demanda de ultrapassagem Convencional
                                    ldblConsumoReativo = IIf(IsDBNull(row.Item("valor_consumo_reativo")), 0, row.Item("valor_consumo_reativo")) * lintMpr 'Consumo Reativo
                                    ldblDemandaReativa = IIf(IsDBNull(row.Item("valor_demanda_reativo")), 0, row.Item("valor_demanda_reativo")) * lintMpr 'Demanda Reativo
                                    'ldblVKwhFatfp = IIf(IsDBNull(row.Item("valor_kwh_faturado_fora_ponta")), 0, row.Item("valor_kwh_faturado_fora_ponta")) * lintMpr 'Consumo faturado fp

                                ElseIf lstrGrupo = "AA" Or lstrGrupo = "AV" Or lstrGrupo = "AL" Or lstrGrupo = "AP" Or lstrGrupo = "AX" Then

                                    'Quantidade
                                    ldblQKwhFatp = 0
                                    ldblQKwhFatfp = 0
                                    ldblQKwhFatpLiv = 0
                                    ldblQKwhFatfpLiv = 0
                                    ldblQKwhFatpAUX = 0
                                    ldblQKwhFatfpAUX = 0


                                    'Micro Geração
                                    If lintMicroGeracaoConvenioSefaz = 0 Then

                                        ldblVKwhReversoCompTEQtde = IIf(IsDBNull(row.Item("qtd_COMP. TE")), 0, row.Item("qtd_COMP. TE"))
                                        ldblVKwhReversoCompTUSDQtde = IIf(IsDBNull(row.Item("qtd_COMP. TUSD")), 0, row.Item("qtd_COMP. TUSD"))

                                        ldblVKwhReversoCompTEVlr = IIf(IsDBNull(row.Item("vlr_COMP. TE")), 0, row.Item("vlr_COMP. TE"))
                                        ldblVKwhReversoCompTUSDVlr = IIf(IsDBNull(row.Item("vlr_COMP. TUSD")), 0, row.Item("vlr_COMP. TUSD"))

                                        ldblQKwhReversop = (ldblVKwhReversoCompTEQtde + ldblVKwhReversoCompTUSDQtde) * lintMpr
                                        ldblVKwhReversop = (ldblVKwhReversoCompTEVlr + ldblVKwhReversoCompTUSDVlr) * lintMpr

                                        'ldblQKwhReversop = BuscaVlrItem(lstrItens, "0302012010") * lintMpr 'Qtde Medido Reverso na ponta ***
                                        ldblQKwhReversofp = IIf(IsDBNull(row.Item("REVERSO_FORA_PONTA")), 0, row.Item("REVERSO_FORA_PONTA")) * lintMpr 'Qtde Medido Reverso fora ponta
                                    Else

                                        ldblVKwhReversoCompTEQtde = IIf(IsDBNull(row.Item("qtd_COMP. TE")), 0, row.Item("qtd_COMP. TE"))
                                        ldblVKwhReversoCompTUSDQtde = IIf(IsDBNull(row.Item("qtd_COMP. TUSD")), 0, row.Item("qtd_COMP. TUSD"))

                                        ldblVKwhReversoCompTEVlr = IIf(IsDBNull(row.Item("vlr_COMP. TE")), 0, row.Item("vlr_COMP. TE"))
                                        ldblVKwhReversoCompTUSDVlr = IIf(IsDBNull(row.Item("vlr_COMP. TUSD")), 0, row.Item("vlr_COMP. TUSD"))

                                        ldblQKwhReversop_sefaz = (ldblVKwhReversoCompTEQtde + ldblVKwhReversoCompTUSDQtde) * lintMpr
                                        ldblVKwhReversop_sefaz = (ldblVKwhReversoCompTEVlr + ldblVKwhReversoCompTUSDVlr) * lintMpr

                                        'ldblQKwhReversop_sefaz = BuscaVlrItem(lstrItens, "0302012010") * lintMpr 'Qtde Medido Reverso na ponta ***
                                        ldblQKwhReversofp_sefaz = IIf(IsDBNull(row.Item("REVERSO_FORA_PONTA")), 0, row.Item("REVERSO_FORA_PONTA")) * lintMpr 'Qtde Medido Reverso fora ponta
                                    End If


                                    'PLD
                                    ldblQKwhDevp = IIf(IsDBNull(row.Item("kwh_devolvido_ponta")), 0, row.Item("kwh_devolvido_ponta"))  'Consumo devolvido na p
                                    ldblQKwhDevfp = IIf(IsDBNull(row.Item("kwh_devolvido_fora_ponta")), 0, row.Item("kwh_devolvido_fora_ponta"))  'Consumo devolvido na fp
                                    If ldblQKwhDevp < 0 Then ldblQKwhDevp = ldblQKwhDevp * -1
                                    If ldblQKwhDevfp < 0 Then ldblQKwhDevfp = ldblQKwhDevfp * -1
                                    ldblQKwhDevp = ldblQKwhDevp * lintMpr 'Consumo devolvido na p
                                    ldblQKwhDevfp = ldblQKwhDevfp * lintMpr 'Consumo devolvido na fp
                                    ldblQKwhUtrp = IIf(IsDBNull(row.Item("kwh_ultrapassado_ponta")), 0, row.Item("kwh_ultrapassado_ponta")) * lintMpr 'Consumo ultrapassado na p
                                    ldblQKwhUtrfp = IIf(IsDBNull(row.Item("kwh_ultrapassado_fora_ponta")), 0, row.Item("kwh_ultrapassado_fora_ponta")) * lintMpr 'Consumo ultrapassado na fp

                                    If ldblQKwhFatp = 0 Then

                                        'ldblQKwhFatp = (BuscaVlrItem(lstrItens, "0302010010")) * lintMpr 'Consumo faturado p 
                                        ldblQKwhFatp = IIf(IsDBNull(row.Item("kwh_faturado_ponta")), 0, row.Item("kwh_faturado_ponta")) * lintMpr

                                        If lintMicroGeracaoConvenioSefaz = 0 Then
                                            If ldblQKwhFatp <= ldblQKwhReversop Then
                                                ldblQKwhReversop = ldblQKwhFatp
                                                ldblQKwhFatp = 0
                                            Else
                                                ldblQKwhFatp = ldblQKwhFatp - ldblQKwhReversop
                                            End If
                                        Else
                                            If ldblQKwhFatp <= ldblQKwhReversop_sefaz Then
                                                ldblQKwhReversop_sefaz = ldblQKwhFatp
                                                ldblQKwhFatp = 0
                                            Else
                                                ldblQKwhFatp = ldblQKwhFatp - ldblQKwhReversop_sefaz
                                            End If
                                        End If

                                        'ldblQKwhFatpBan = (BuscaVlrItem(lstrItens, "0302110010")) * lintMpr 'Consumo faturado p bandeira ****

                                        If ldblQKwhFatpBan > 0 Then
                                            If ldblQKwhFatpBan <= ldblQKwhFatpAUX Then
                                                ldblQKwhFatpBan = 0
                                            Else
                                                ldblQKwhFatpBan = ldblQKwhFatpBan - ldblQKwhFatpAUX
                                            End If
                                        End If

                                        If lstrGrupo = "AL" Then
                                            If lintParcialmenteCativo = 1 Then
                                                ldblQKwhFatpLiv = IIf(IsDBNull(row.Item("kwh_faturado_ponta")), 0, row.Item("kwh_faturado_ponta")) * lintMpr 'Consumo faturado p
                                                ldblQKwhFatp = ldblQKwhFatp - ldblQKwhFatpLiv
                                                'ldblQKwhFatpBan = ldblQKwhFatpBan - ldblQKwhFatpLiv
                                            Else
                                                ldblQKwhFatpLiv = IIf(IsDBNull(row.Item("kwh_faturado_ponta")), 0, row.Item("kwh_faturado_ponta")) * lintMpr 'Consumo faturado p
                                                ldblQKwhFatp = ldblQKwhFatp - ldblQKwhFatpLiv
                                                If ldblQKwhFatpBan >= 0 Then ldblQKwhFatpBan = 0
                                            End If
                                        End If

                                    End If

                                    If ldblQKwhFatfp = 0 Then

                                        ldblQKwhFatfp = IIf(IsDBNull(row.Item("kwh_faturado_fora_ponta")), 0, row.Item("kwh_faturado_fora_ponta")) * lintMpr 'Consumo faturado fp

                                        If lintMicroGeracaoConvenioSefaz = 0 Then
                                            If ldblQKwhFatfp <= ldblQKwhReversofp Then
                                                ldblQKwhReversofp = ldblQKwhFatfp
                                                ldblQKwhFatfp = 0
                                            Else
                                                ldblQKwhFatfp = ldblQKwhFatfp - ldblQKwhReversofp
                                            End If
                                        Else
                                            If ldblQKwhFatfp <= ldblQKwhReversofp_sefaz Then
                                                ldblQKwhReversofp_sefaz = ldblQKwhFatfp
                                                ldblQKwhFatfp = 0
                                            Else
                                                ldblQKwhFatfp = ldblQKwhFatfp - ldblQKwhReversofp_sefaz
                                            End If
                                        End If

                                        'ldblQKwhFatfpBan = (BuscaVlrItem(lstrItens, "0302110011")) * lintMpr 'Consumo faturado fp ****

                                        If ldblQKwhFatfpBan > 0 Then
                                            If ldblQKwhFatfpBan <= ldblQKwhFatfpAUX Then
                                                ldblQKwhFatfpBan = 0
                                            Else
                                                ldblQKwhFatfpBan = ldblQKwhFatfpBan - ldblQKwhFatfpAUX
                                            End If
                                        End If

                                        If lstrGrupo = "AL" Then
                                            If lintParcialmenteCativo = 1 Then
                                                ldblQKwhFatfpLiv = IIf(IsDBNull(row.Item("kwh_faturado_fora_ponta")), 0, row.Item("kwh_faturado_fora_ponta")) * lintMpr 'Consumo faturado fp
                                                ldblQKwhFatfp = ldblQKwhFatfp - ldblQKwhFatfpLiv
                                                'ldblQKwhFatfpBan = ldblQKwhFatfpBan - ldblQKwhFatfpLiv
                                            Else
                                                ldblQKwhFatfpLiv = IIf(IsDBNull(row.Item("kwh_faturado_fora_ponta")), 0, row.Item("kwh_faturado_fora_ponta")) * lintMpr 'Consumo faturado fp
                                                ldblQKwhFatfp = ldblQKwhFatfp - ldblQKwhFatfpLiv
                                                If ldblQKwhFatfpBan >= 0 Then ldblQKwhFatfpBan = 0
                                            End If
                                        End If

                                    End If

                                    ldblQKwhCons = IIf(IsDBNull(row.Item("valor_total")), 0, row.Item("valor_total")) * lintMpr 'ldblQKwhFatp + ldblQKwhFatfp '+ ldblQKwFatp + ldblQKwFatfp

                                    If lintMicroGeracaoConvenioSefaz = 0 Then
                                        ldblVKwhReversop = IIf(IsDBNull(row.Item("REVERSO PONTA")), 0, row.Item("REVERSO PONTA")) * lintMpr 'valor Medido Reverso na ponta
                                        ldblVKwhReversofp = IIf(IsDBNull(row.Item("REVERSO FORA DE PONTA")), 0, row.Item("REVERSO FORA DE PONTA")) * lintMpr 'valor Medido Reverso fora ponta
                                    Else
                                        ldblVKwhReversop_sefaz = IIf(IsDBNull(row.Item("REVERSO PONTA")), 0, row.Item("REVERSO PONTA")) * lintMpr 'valor Medido Reverso na ponta
                                        ldblVKwhReversofp_sefaz = IIf(IsDBNull(row.Item("REVERSO FORA DE PONTA")), 0, row.Item("REVERSO FORA DE PONTA")) * lintMpr 'valor Medido Reverso fora ponta
                                    End If
                                    '
                                    ldblQKwContr = IIf(IsDBNull(row.Item("demanda_contratada_ponta")), 0, row.Item("demanda_contratada_ponta"))  'Demanda Contratada p
                                    ldblQKwContr = IIf(IsDBNull(row.Item("demanda_contratada_fora_ponta")), 0, row.Item("demanda_contratada_fora_ponta"))  'Demanda Contratada fp
                                    ldblQKwFatp = IIf(IsDBNull(row.Item("kw_faturado_ponta")), 0, row.Item("kw_faturado_ponta")) * lintMpr  ' + BuscaVlrItem(lstrItens, "0302010022")  'Demanda p
                                    ldblQKwFatfp = IIf(IsDBNull(row.Item("kw_faturado_fora_ponta")), 0, row.Item("kw_faturado_fora_ponta")) * lintMpr ' + BuscaVlrItem(lstrItens, "0302010026") 'Demanda fp

                                    ldblQKwFatUp = IIf(IsDBNull(row.Item("kw_ultrapassagem_ponta")), 0, row.Item("kw_ultrapassagem_ponta")) * lintMpr 'Demanda de ultrapassagem p
                                    ldblQKwFatUfp = IIf(IsDBNull(row.Item("kw_ultrapassado_fora_ponta")), 0, row.Item("kw_ultrapassado_fora_ponta")) * lintMpr 'Demanda de ultrapassagem fp

                                    If ldblDiferenca <> 0 Then
                                        ldblVKwhReversop = ldblVKwhReversop + ldblDiferenca '(ldblDiferenca * -1)
                                        ldblDiferencaTot = ldblDiferencaTot + ldblDiferenca
                                    End If

                                    'Valor
                                    ldblVKwhFatp = 0
                                    ldblVKwhFatfp = 0
                                    ldblVKwhFatpLiv = 0
                                    ldblVKwhFatfpLiv = 0
                                    'ldblTarPSeca = BuscaVlrItem(lstrItens, "01AV011101") 'Tarifa Consumo Lido na Ponta
                                    'ldblTarFPSeca = BuscaVlrItem(lstrItens, "01AV011102") 'Tarifa Consumo Lido na Fora Ponta
                                    'ldblTarPUmida = BuscaVlrItem(lstrItens, "01AV011105") 'Tarifa Consumo Lido na Ponta
                                    'ldblTarFPUmida = BuscaVlrItem(lstrItens, "01AV011106") 'Tarifa Consumo Lido na Fora Ponta
                                    ldblVKwhFatp = IIf(IsDBNull(row.Item("valor_kwh_faturado_ponta")), 0, row.Item("valor_kwh_faturado_ponta")) * lintMpr 'Consumo faturado p
                                    ldblVKwhFatpBan = IIf(IsDBNull(row.Item("bandeira_valor_kwh_fat_ponta")), 0, row.Item("bandeira_valor_kwh_fat_ponta")) * lintMpr 'Consumo faturado p

                                    If lstrGrupo = "AL" Then
                                        If lintParcialmenteCativo = 1 Then
                                            ldblVKwhFatpLiv = IIf(IsDBNull(row.Item("valor_kwh_faturado_ponta")), 0, row.Item("valor_kwh_faturado_ponta")) * lintMpr 'Consumo faturado p
                                        Else
                                            ldblVKwhFatpLiv = IIf(IsDBNull(row.Item("valor_kwh_faturado_ponta")), 0, row.Item("valor_kwh_faturado_ponta")) * lintMpr 'Consumo faturado p
                                            ldblVKwhFatp = ldblVKwhFatp - ldblVKwhFatpLiv
                                            If ldblVKwhFatpBan >= 0 Then ldblVKwhFatpBan = 0
                                        End If
                                    End If

                                    ldblVKwhFatfp = IIf(IsDBNull(row.Item("valor_kwh_faturado_fora_ponta")), 0, row.Item("valor_kwh_faturado_fora_ponta")) * lintMpr 'Consumo faturado fp
                                    ldblVKwhFatfpBan = IIf(IsDBNull(row.Item("bandeira_valor_kwh_fat_fora_ponta")), 0, row.Item("bandeira_valor_kwh_fat_fora_ponta")) * lintMpr 'Consumo faturado fp

                                    If lstrGrupo = "AL" Then
                                        If lintParcialmenteCativo = 1 Then
                                            ldblVKwhFatfpLiv = IIf(IsDBNull(row.Item("valor_kwh_faturado_fora_ponta")), 0, row.Item("valor_kwh_faturado_fora_ponta")) * lintMpr 'Consumo faturado fp
                                        Else
                                            ldblVKwhFatfpLiv = IIf(IsDBNull(row.Item("valor_kwh_faturado_fora_ponta")), 0, row.Item("valor_kwh_faturado_fora_ponta")) * lintMpr 'Consumo faturado fp
                                            ldblVKwhFatfp = ldblVKwhFatfp - ldblVKwhFatfpLiv
                                            If ldblVKwhFatfpBan >= 0 Then ldblVKwhFatfpBan = 0
                                        End If
                                    End If

                                    ldblVKwhDevp = IIf(IsDBNull(row.Item("valor_kwh_devolvido_ponta")), 0, row.Item("valor_kwh_devolvido_ponta")) * lintMpr 'Valor Consumo devolvido na p
                                    ldblVKwhDevfp = IIf(IsDBNull(row.Item("valor_kwh_devolvido_fora_ponta")), 0, row.Item("valor_kwh_devolvido_fora_ponta")) * lintMpr 'Valor Consumo devolvido na fp
                                    ldblVKwhUtrp = IIf(IsDBNull(row.Item("valor_kwh_ultrapassado_ponta")), 0, row.Item("valor_kwh_ultrapassado_ponta")) * lintMpr 'Valor Consumo ultrapassado na p
                                    ldblVKwhUtrfp = IIf(IsDBNull(row.Item("valor_kwh_ultrapassado_fora_ponta")), 0, row.Item("valor_kwh_ultrapassado_fora_ponta")) * lintMpr 'Valor Consumo ultrapassado na fp


                                    ldblVKwhCons = IIf(IsDBNull(row.Item("vlr_kwh_faturado")), 0, row.Item("vlr_kwh_faturado")) * lintMpr
                                    'ldblVKwhCons = ldblVKwhFatp + ldblVKwhFatfp '+ ldblVKwFatp + ldblVKwFatfp
                                    ldblVKwFatp = IIf(IsDBNull(row.Item("valor_kw_faturado_ponta")), 0, row.Item("valor_kw_faturado_ponta")) * lintMpr ' + BuscaVlrItem(lstrItens, "0302020022")  'Demanda p
                                    ldblVKwFatfp = IIf(IsDBNull(row.Item("valor_kw_faturado_fora_ponta")), 0, row.Item("valor_kw_faturado_fora_ponta")) * lintMpr '+ (BuscaVlrItem(lstrItens, "0302020072") * lintMpr) ' + BuscaVlrItem(lstrItens, "0302020026") 'Demanda fp

                                    ''Arlindo dif. demanda
                                    ldblVKwDifFatp = 0 'IIf(IsDBNull(row.Item("valor_kw_faturado_fora_ponta")), 0, row.Item("valor_kw_faturado_fora_ponta")) * lintMpr ' 'Dif. Demanda p
                                    ldblVKwDifFatfp = IIf(IsDBNull(row.Item("valor_dif dem contr")), 0, row.Item("valor_dif dem contr")) * lintMpr 'Dif. Demanda fp
                                    '

                                    If lstrGrupo = "AL" Then
                                        'ldblVKwFatp = ldblVKwFatp + (BuscaVlrItem(lstrItens, "0302060021") * lintMpr) 'dif.Demanda p ***
                                        'ldblVKwFatfp = ldblVKwFatfp + (BuscaVlrItem(lstrItens, "0302060025") * lintMpr) 'dif.Demanda fp ***
                                        ldblVkwDscProv = IIf(IsDBNull(row.Item("valor_desconto_provisorio")), 0, row.Item("valor_desconto_provisorio")) * lintMpr 'Desconto Provisorio
                                        ldblVkwDscReal = IIf(IsDBNull(row.Item("valor_desconto_realizado")), 0, row.Item("valor_desconto_realizado")) * lintMpr 'Desconto real
                                        ldblVkwDevCcee = IIf(IsDBNull(row.Item("valor_devolucao_diferenca_ccee")), 0, row.Item("valor_devolucao_diferenca_ccee")) * lintMpr 'diferença a devolver
                                        ldblVkwCobCcee = IIf(IsDBNull(row.Item("valor_cobranca_diferenca_ccee")), 0, row.Item("valor_cobranca_diferenca_ccee")) * lintMpr 'diferença a cobrar
                                        '
                                        ldblVkwhDscProv = IIf(IsDBNull(row.Item("valor_energia_desconto_provisorio")), 0, row.Item("valor_energia_desconto_provisorio")) * lintMpr 'Desconto Provisorio
                                        ldblVkwhDscReal = IIf(IsDBNull(row.Item("valor_energia_desconto_realizado")), 0, row.Item("valor_energia_desconto_realizado")) * lintMpr 'Desconto real
                                        ldblVkwhDevCcee = IIf(IsDBNull(row.Item("valor_energia_devolucao_diferenca_ccee")), 0, row.Item("valor_energia_devolucao_diferenca_ccee")) * lintMpr 'diferença a devolver
                                        ldblVkwhCobCcee = IIf(IsDBNull(row.Item("valor_energia_cobranca_diferenca_ccee")), 0, row.Item("valor_energia_cobranca_diferenca_ccee")) * lintMpr 'diferença a cobrar
                                    End If

                                    ldblVKwFatUp = IIf(IsDBNull(row.Item("valor_kw_ultrapassagem_ponta")), 0, row.Item("valor_kw_ultrapassagem_ponta")) * lintMpr 'Demanda de ultrapassagem p
                                    ldblVKwFatUfp = IIf(IsDBNull(row.Item("valor_kw_ultrapassado_fora_ponta")), 0, row.Item("valor_kw_ultrapassado_fora_ponta")) * lintMpr 'Demanda de ultrapassagem fp

                                End If

                                'Reativo
                                ldblConsumoReativop = IIf(IsDBNull(row.Item("valor_consumo_reativo_ponta")), 0, row.Item("valor_consumo_reativo_ponta")) * lintMpr 'Consumo Reativo p
                                ldblConsumoReativofp = IIf(IsDBNull(row.Item("valor_consumo_reativo_fora_ponta")), 0, row.Item("valor_consumo_reativo_fora_ponta")) * lintMpr 'Consumo Reativo fp
                                ldblDemandaReativap = IIf(IsDBNull(row.Item("valor_demanda_reativo_ponta")), 0, row.Item("valor_demanda_reativo_ponta")) * lintMpr 'Demanda Reativo p
                                ldblDemandaReativafp = IIf(IsDBNull(row.Item("valor_demanda_reativo_fora_ponta")), 0, row.Item("valor_demanda_reativo_fora_ponta")) * lintMpr 'Demanda Reativo fp

                                ldblTip = IIf(IsDBNull(row.Item("valor_cip")), 0, row.Item("valor_cip")) * lintMpr 'Vlr Iluminação Pública.


                                'Tributos
                                ldblIcms1 = IIf(IsDBNull(row.Item("valor_icms")), 0, row.Item("valor_icms")) * lintMpr 'Vlr Icms.
                                ldblIcms2 = IIf(IsDBNull(row.Item("valor_icms")), 0, row.Item("valor_icms")) * lintMpr 'Vlr Icms.
                                ldblPis = IIf(IsDBNull(row.Item("valor_pis")), 0, row.Item("valor_pis")) * lintMpr 'Vlr PIS.
                                ldblCofins = IIf(IsDBNull(row.Item("valor_cofins")), 0, row.Item("valor_cofins")) * lintMpr 'Vlr COFINS.
                                'ldblIcmsSt = IIf(IsDBNull(row.Item("valor_cip")), 0, row.Item("valor_cip")) * lintMpr ***
                                'ldblPisSt = IIf(IsDBNull(row.Item("valor_cip")), 0, row.Item("valor_cip")) * lintMpr ***
                                'ldblCofinsSt = IIf(IsDBNull(row.Item("valor_cip")), 0, row.Item("valor_cip")) * lintMpr ***
                                'ldblIcmsPisCof = IIf(IsDBNull(row.Item("valor_cip")), 0, row.Item("valor_cip")) * lintMpr 'Vlr Icms/Pis/Cofins. ***
                                'ldblSaldoArre = IIf(IsDBNull(row.Item("valor_cip")), 0, row.Item("valor_cip")) * lintMpr ***
                                ldblJuros = IIf(IsDBNull(row.Item("valor_juros_ece")), 0, row.Item("valor_juros_ece")) * lintMpr 'Juros verificar ainda com o calculo.
                                ldblEncargo = IIf(IsDBNull(row.Item("valor_ece")), 0, row.Item("valor_ece")) * lintMpr 'Encargos confirma ainda com o calculo
                                ldblMust = IIf(IsDBNull(row.Item("valor_must")), 0, row.Item("valor_must")) * lintMpr 'EUSD - Must das usinas (EFLUL)

                                ldblTaxados = IIf(IsDBNull(row.Item("valor_taxados")), 0, row.Item("valor_taxados")) * lintMpr
                                ldblDiversos = IIf(IsDBNull(row.Item("valor_diversos")), 0, row.Item("valor_diversos")) * lintMpr
                                ldblEncFinan = IIf(IsDBNull(row.Item("valor_encargos_financeiros")), 0, row.Item("valor_encargos_financeiros")) * lintMpr
                                ldblConvenios = IIf(IsDBNull(row.Item("valor_convenios")), 0, row.Item("valor_convenios")) * lintMpr
                                ldblRetencao = IIf(IsDBNull(row.Item("valor_retencao")), 0, row.Item("valor_retencao")) * lintMpr
                                ldblDevolucao = IIf(IsDBNull(row.Item("valor_devolucao")), 0, row.Item("valor_devolucao")) * lintMpr


                                'Isento icms
                                ldblIsentoIcms = 0

                                If ldblIcms1 = 0 Then
                                    ldblIsentoIcms = ldblBaseIcms1
                                End If
                                If ldblIcms2 = 0 Then
                                    ldblIsentoIcms = ldblIsentoIcms + ldblBaseIcms2
                                End If


                                Dim sRepartItens
                                Dim i As Integer
                                Dim sRepartCodServ
                                Dim PCif As Long
                                Dim lvlrCodSrv As String
                                Dim ldlbCodSrv As Double

                                sRepartItens = Split(lstrItens, ";")

                                For i = 0 To UBound(sRepartItens) - 1

                                    lblnInclui = False

                                    sRepartCodServ = Split(sRepartItens(i), "?")
                                    CodServ = sRepartCodServ(0)

                                    PCif = Strings.InStr(1, sRepartCodServ(1), "$")

                                    If PCif > 0 Then
                                        lvlrCodSrv = Mid(sRepartCodServ(1), 1, Strings.InStr(1, sRepartCodServ(1), "$") - 1)
                                        lvlrCodSrv = lvlrCodSrv.Replace(",", ".")

                                        ldlbCodSrv = CDbl(Replace(IIf(IsNumeric(lvlrCodSrv), lvlrCodSrv, 0), ".", ","))
                                    Else
                                        lvlrCodSrv = sRepartCodServ(1)
                                        lvlrCodSrv = lvlrCodSrv.Replace(",", ".")

                                        ldlbCodSrv = CDbl(Replace(IIf(IsNumeric(lvlrCodSrv), lvlrCodSrv, 0), ".", ","))
                                    End If


                                    If (ldlbCodSrv < 0) And (Mid(CodServ, 1, 4) <> "9080") And lstrGrupo <> "AX" Then
                                        ldlbCodSrv = ldlbCodSrv * -1
                                    End If

                                    'Taxas
                                    If (Mid(CodServ, 1, 4) = "9040") Or (Mid(CodServ, 1, 4) = "9050") Then
                                        ' ldblVlrTax = ldblVlrTax + ldlbCodSrv
                                        lblnInclui = True
                                    End If

                                    'Outros (EUSD - MUST
                                    If CodServ = "0302020032" Then
                                        'ldblVlrOut = ldblVlrOut + ldlbCodSrv
                                        lblnInclui = True
                                    End If

                                    '
                                    'Diversos
                                    If Mid(CodServ, 1, 4) = "9080" Then
                                        'ldblVlrDiv = ldblVlrDiv + ldlbCodSrv
                                        lblnInclui = True
                                    End If

                                    '
                                    'Convenios
                                    If Mid(CodServ, 1, 4) = "9030" And CodServ <> "90303" And CodServ <> "90304" Then
                                        'ldblVlrCov = ldblVlrCov + ldlbCodSrv
                                        lblnInclui = True
                                    End If

                                    '
                                    'Descontos
                                    If (Mid(CodServ, 1, 4) = "9070") And (CodServ <> "9070000088") Then
                                        'ldblVlrDes = ldblVlrDes + ldlbCodSrv
                                        lblnInclui = True
                                    End If

                                    '
                                    'Retencoes
                                    If (CodServ = "9070000088") Or (Mid(CodServ, 1, 4) = "9090") Then
                                        'ldblVlrRet = ldblVlrRet + ldlbCodSrv
                                        lblnInclui = True
                                    End If

                                    If (CodServ = "0302020051") Or (CodServ = "0302020052") Or (CodServ = "0302020053") Or (CodServ = "0302020054") Or (CodServ = "0302020055") Or (CodServ = "0302020056") Or (CodServ = "0302020057") Or (CodServ = "0302020058") Then
                                        If CDbl(VB.Right(CodServ, 1)) <> 4 And CDbl(VB.Right(CodServ, 1)) <> 8 Then
                                            If ldlbCodSrv > 0 Then
                                                ldlbCodSrv = ldlbCodSrv * (-1)
                                            End If
                                        End If
                                        lblnInclui = True
                                    End If

                                    '
                                    'Substituição Tributária
                                    If (CodServ = "0602020001" Or CodServ = "0602020002" Or CodServ = "0602020003") Then
                                        lblnInclui = True
                                    End If

                                    'COOPERATIVA
                                    'If CDbl(lstrClas) = 5201 Then
                                    '    lblnInclui = True
                                    'End If


                                    If lblnInclui = True Then

                                        lstrSqlIAx = lstrSqlIAx & "('" & CodServ & "','" & codTodescri(CodServ) & "'" & "," & Replace(CStr(ldlbCodSrv * lintMpr), ",", ".") & ",'" & lstrZona & "'" & ",'" & Microsoft.VisualBasic.Left(lstrGrupo, 1) & "'), "

                                        lintContInsertItens = lintContInsertItens + 1

                                        If lintContInsertItens > 300 Then
                                            lstrSqlIte = lstrSqlIte & Microsoft.VisualBasic.Left(lstrSqlIAx, Len(lstrSqlIAx) - 2)
                                            objTempEstatisItens.TABLE = lstrSqlIte
                                            repositorioTempEstatisItens.Execute_2(objTempEstatisItens)

                                            lstrSqlIte = ""

                                            If CriaTabelas(lstrSqlPri, lstrSqlIte, False, False, True) Then
                                                lstrSqlIAx = ""
                                                lintContInsertItens = 1
                                            End If


                                        End If

                                    End If

                                Next


                                lstrSqlPAx = lstrSqlPAx & "('" & lstrClasse & "', " 'classe

                                'Convencional
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhCons), ",", ".") & "', " 'qkwh_cons
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFat), ",", ".") & "', " 'qkwh_fat
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatBan), ",", ".") & "', " 'qkwh_fat_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwContr), ",", ".") & "', " 'qkw_contr
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwFat), ",", ".") & "', " 'qkw_fat
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhCons), ",", ".") & "', " 'vkwh_cons

                                If (ldblVkWhFatTU + ldblVkWhFatTE) > 0 Then
                                    lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkWhFatTU + ldblVkWhFatTE), ",", ".") & "', " 'vkwh_fat
                                    lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkWhFatTEBan), ",", ".") & "', " 'vkwh_fat_ban
                                Else
                                    lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFat), ",", ".") & "', " 'vkwh_fat
                                    lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatBan), ",", ".") & "', " 'vkwh_fat_ban
                                End If

                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwFat), ",", ".") & "', " 'vkw_fat
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblConsumoReativo), ",", ".") & "', " 'vconreat
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblDemandaReativa), ",", ".") & "', " 'vdemreat

                                'Horosazonal
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatp), ",", ".") & "', " 'qkwh_fat_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFati), ",", ".") & "', " 'qkwh_fat_i
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatfp), ",", ".") & "', " 'qkwh_fat_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatpBan), ",", ".") & "', " 'qkwh_fat_p_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatiBan), ",", ".") & "', " 'qkwh_fat_i_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatfpBan), ",", ".") & "', " 'qkwh_fat_fp_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatpLiv), ",", ".") & "', " 'qkwh_fat_p_liv
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatfpLiv), ",", ".") & "', " 'qkwh_fat_fp_liv
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhDevp), ",", ".") & "', " 'qkwh_dev_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhDevfp), ",", ".") & "', " 'qkwh_dev_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhUtrp), ",", ".") & "', " 'qkwh_utr_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhUtrfp), ",", ".") & "', " 'qkwh_utr_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwContrp), ",", ".") & "', " 'qkw_contr_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwContrfp), ",", ".") & "', " 'qkw_contr_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwFatp), ",", ".") & "', " 'qkw_fat_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwFatfp), ",", ".") & "', " 'qkw_fat_fp

                                ' Arlindo dif. demanda
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwDifFatp), ",", ".") & "', " 'qkw_dif_fat_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwDifFatfp), ",", ".") & "', " 'qkw_dif_fat_fp
                                '

                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwFatUp), ",", ".") & "', " 'qkw_fatu_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwFatUfp), ",", ".") & "', " 'qkw_fatu_fp

                                'valor
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatp), ",", ".") & "', " 'vkwh_fat_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFati), ",", ".") & "', " 'vkwh_fat_i
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatfp), ",", ".") & "', " 'vkwh_fat_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatpBan), ",", ".") & "', " 'vkwh_fat_p_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatiBan), ",", ".") & "', " 'vkwh_fat_i_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatfpBan), ",", ".") & "', " 'vkwh_fat_fp_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatpLiv), ",", ".") & "', " 'vkwh_fat_p_liv
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatfpLiv), ",", ".") & "', " 'vkwh_fat_fp_liv
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhDevp), ",", ".") & "', " 'vkwh_dev_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhDevfp), ",", ".") & "', " 'vkwh_dev_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhUtrp), ",", ".") & "', " 'vkwh_utr_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhUtrfp), ",", ".") & "', " 'vkwh_utr_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwFatp), ",", ".") & "', " 'vkw_fat_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwFatfp), ",", ".") & "', " 'vkw_fat_fp

                                ' Arlindo dif. demanda
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwDifFatp), ",", ".") & "', " 'vkw_dif_fat_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwDifFatfp), ",", ".") & "', " 'vkw_dif_fat_fp
                                '

                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwFatUp), ",", ".") & "', " 'vkw_fatu_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwFatUfp), ",", ".") & "', " 'vkw_fatu_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwDscProv), ",", ".") & "', " 'vkw_dsc_prov
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwDscReal), ",", ".") & "', " 'vkw_dsc_real
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwDevCcee), ",", ".") & "', " 'vkw_dev_ccee
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwCobCcee), ",", ".") & "', " 'vkw_cob_ccee

                                '
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwhDscProv), ",", ".") & "', " 'vkwh_dsc_prov
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwhDscReal), ",", ".") & "', " 'vkwh_dsc_real
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwhDevCcee), ",", ".") & "', " 'vkwh_dev_ccee
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwhCobCcee), ",", ".") & "', " 'vkwh_cob_ccee
                                '

                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblConsumoReativop), ",", ".") & "', " 'vconreat_p = Consumo Reativo ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblConsumoReativofp), ",", ".") & "', " 'vconreat_fp = Consumo Reativo fora ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblDemandaReativap), ",", ".") & "', " 'vdemreat_p = Demanda Reativo ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblDemandaReativafp), ",", ".") & "', " 'vdemreat_fp = Demanda Reativo fora ponta
                                'lstrSqlPAx = lstrSqlPAx & "'" & Replace(ldblQKwhReverso, ",", ".") & "', " 'reverso
                                'lstrSqlPAx = lstrSqlPAx & "'" & Replace(ldblVKwhReverso, ",", ".") & "', " 'valor
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhReversop), ",", ".") & "', " 'Qtd Medido reverso ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhReversoi), ",", ".") & "', " 'Qtd Medido reverso intermediario
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhReversofp), ",", ".") & "', " 'Qtd Medido reverso fora ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhReversop), ",", ".") & "', " 'valor Medido reverso ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhReversoi), ",", ".") & "', " 'valor Medido reverso intermediario
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhReversofp), ",", ".") & "', " 'valor Medido reverso fora ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhReversop_sefaz), ",", ".") & "', " 'Qtd Medido reverso ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhReversoi_sefaz), ",", ".") & "', " 'Qtd Medido reverso intermediario
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhReversofp_sefaz), ",", ".") & "', " 'Qtd Medido reverso fora ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhReversop_sefaz), ",", ".") & "', " 'valor Medido reverso ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhReversoi_sefaz), ",", ".") & "', " 'valor Medido reverso intermediario
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhReversofp_sefaz), ",", ".") & "', " 'valor Medido reverso fora ponta

                                'Outros
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblTip), ",", ".") & "', " 'tip
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblSaldoArre), ",", ".") & "', " 'arrendodamento
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblEncFinan), ",", ".") & "', " 'encargos financeiros
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblIcms1 + ldblIcms2), ",", ".") & "', " 'icms
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblPis), ",", ".") & "', " 'pis
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblCofins), ",", ".") & "', " 'cofins
                                '
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblIcmsSt), ",", ".") & "', " 'icms - st
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblPisSt), ",", ".") & "', " 'pis - st
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblCofinsSt), ",", ".") & "', " 'cofins - st
                                '
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblBaseIcms1 + ldblBaseIcms2), ",", ".") & "', " 'base icms
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblBasePis), ",", ".") & "', " 'base pis
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblBaseCofins), ",", ".") & "', " 'base cofins
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblIcmsPisCof), ",", ".") & "', " 'icms/pis/cofins
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblIsentoIcms), ",", ".") & "', " 'Isento icms
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblDiferido), ",", ".") & "', " 'diferido
                                '
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblDifEltrbr), ",", ".") & "', " 'dif_eltrbr
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblJuros), ",", ".") & "', " 'juros
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblEncargo), ",", ".") & "', " 'encargo
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblMust), ",", ".") & "', " 'must
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblValorTot)), ",", ".") & "', " 'total
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblTaxados)), ",", ".") & "', " 'taxados
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblDiversos)), ",", ".") & "', " 'diversos
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblConvenios)), ",", ".") & "', " 'convenios
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblDevolucao)), ",", ".") & "', " 'descontos
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblDevolucao_1)), ",", ".") & "', " 'descontos_1
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblRetencao)), ",", ".") & "', " 'retencao
                                '
                                lstrSqlPAx = lstrSqlPAx & "'" & lstrFlgMedFat & "', " 'flgmedtfat = Fatura que foi cancelada e reprocessada
                                lstrSqlPAx = lstrSqlPAx & "'" & lintFaturaFinal & "', " 'fatura_final
                                lstrSqlPAx = lstrSqlPAx & "'" & lintIrrigacaoAquicultura & "', " 'irrigacao_aquicultura

                                lstrSqlPAx = lstrSqlPAx & "'" & lintMicroGeracao & "', " 'micro geracao
                                lstrSqlPAx = lstrSqlPAx & "'" & lintMicroGeracaoDistribuida & "', " 'micro geracao
                                lstrSqlPAx = lstrSqlPAx & "'" & lintMicroGeracaoConvenioSefaz & "', " 'micro geracao convenio Sefaz
                                lstrSqlPAx = lstrSqlPAx & "'" & lintTarifaBranca & "', " 'tarifa_branca

                                '************************************

                                If lintMicroGeracaoConvenioSefaz = 0 Then
                                    'lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblVKwhReverso + ldblVKwhReversop + ldblVKwhReversofp)), ",", ".") & "', " 'reverso para o importe
                                    lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblVKwhReversop + ldblVKwhReversoi + ldblVKwhReversofp)), ",", ".") & "', " 'reverso para o importe
                                Else
                                    lstrSqlPAx = lstrSqlPAx & "'0',"
                                End If

                                lstrSqlPAx = lstrSqlPAx & "'" & lstrFlgSt & "', " 'situação
                                '
                                lstrSqlPAx = lstrSqlPAx & "'" & lstrFase & "', " 'fase

                                lstrGrupo = IIf(Microsoft.VisualBasic.Left(lstrGrupo, 1) = "A", lstrGrupo, Microsoft.VisualBasic.Left(lstrGrupo, 1))

                                If lstrGrupo = "AL" Then
                                    lstrGrupo = lstrGrupo & IIf(lintParcialmenteCativo = 1, "P", "")
                                    lstrGrupo = lstrGrupo & IIf(lintLivreVerde = 1, "V", "A")
                                End If

                                lstrSqlPAx = lstrSqlPAx & "'" & lstrGrupo & "',"
                                lstrSqlPAx = lstrSqlPAx & "'" & lstrZona & "','" & lstrLivro & "','" & lstrConta & "','" & Replace(lstrNome, "'", "\'") & "',"

                                If lstrGrupoT = "AL" Then
                                    lstrGrupoT = lstrGrupoT & IIf(lintParcialmenteCativo = 1, "P", "")
                                    lstrGrupoT = lstrGrupoT & IIf(lintLivreVerde = 1, "V", "A")
                                End If

                                lstrSqlPAx = lstrSqlPAx & "'" & lstrGrupoT & "',"

                                If lstrGrupoT = "ALA" Then
                                    lintSequencia = 1
                                ElseIf lstrGrupoT = "ALPA" Then
                                    lintSequencia = 2
                                ElseIf lstrGrupoT = "ALV" Then
                                    lintSequencia = 3
                                ElseIf lstrGrupoT = "ALPV" Then
                                    lintSequencia = 4
                                Else
                                    lintSequencia = 0
                                End If

                                lstrSqlPAx = lstrSqlPAx & "'" & lintSequencia & "',"
                                'lstrSqlPAx = lstrSqlPAx & "'" & lstrMesAno & "'"
                                'lstrSqlPAx = lstrSqlPAx & "'" & llngMatricula & "'"

                                lstrSqlPAx = lstrSqlPAx & "'" & lstrMesAno & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & llngMatricula & "',"
                                lstrSqlPAx = lstrSqlPAx & "'" & dNumNf & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & sGrupo_tarifario & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & sClasse_faturada & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & sDescricao_classe & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & sMesano_referencia & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & sAnomes_fat & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(ldteEmissao, "yyyy-MM-dd") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(ldteApresentacao, "yyyy-MM-dd") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(dData_vencimento, "yyyy-MM-dd") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(dData_leitura_atual, "yyyy-MM-dd") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(dData_leitura_anterior, "yyyy-MM-dd") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_juros_ece)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_diferenca_ece)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_ece)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_liquido)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dqtde_fx1)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dqtde_fx2)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dqtde_fx3)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dqtde_fx4)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvlr_fx1)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvlr_fx2)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvlr_fx3)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvlr_fx4)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dkwh_lido)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dbase_icms_1)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(daliquota_icms_1)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_icms_1)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dbase_icms_2)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(daliquota_icms_2)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_icms_2)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dAliquota_PIS)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dAliquota_COFINS)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dreceitas_financeiras)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dressarcimento_idqual)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_encargo_uso_sis_trans)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ddesconto_must)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dencargo_kwh_faturado_ponta)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dencargo_valor_kwh_faturado_ponta)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dencargo_kwh_faturado_fora_ponta)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dencargo_valor_kwh_faturado_fora_ponta)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dmwh_medio)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dmwh_medio_horas)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dVALOR_REVERSO)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dVALOR_REVERSO_BAN)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_PONTA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_PONTA_BANDEIRA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_FORA_DE_PONTA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_FORA_DE_PONTA_BANDEIRA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dbandeira_vlr_kwh_fat)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dbandeira_valor_kwh_fat_ponta)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dbandeira_valor_kwh_fat_fora_ponta)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_energia_desconto_provisorio)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_energia_desconto_realizado)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_energia_devolucao_diferenca_ccee)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_energia_cobranca_diferenca_ccee)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dCONSUMO_PONTA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dCONSUMO_FORA_PONTA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_FORA_PONTA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_RESIDUO_FORA_PONTA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dTUSD)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dCONSUMO_MEDIDO)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_LIDO)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(ddatast, "yyyy-MM-dd") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(ddata_pagamento, "yyyy-MM-dd") & "' "
                                lstrSqlPAx = lstrSqlPAx & "), "
                                lintContInsertPri = lintContInsertPri + 1

                                'If bPlan = True Then

                                '    sGeraPlan_(sGrupo_tarifario, lstrGrupo, lstrClasse, sClasse_faturada, sDescricao_classe, lstrZona, lstrLivro,
                                '               lstrConta, llngMatricula, lstrNome, dNumNf, lstrMesAno, sMesano_referencia, sAnomes_fat, dData_emissao,
                                '               dData_apresentacao, dData_vencimento, dData_leitura_atual, dData_leitura_anterior,
                                '               ldblConsumoReativo, ldblDemandaReativa, ldblConsumoReativop, ldblConsumoReativofp,
                                '               ldblDemandaReativap, ldblDemandaReativafp, ldblQKwFat, ldblVKwFat, ldblQKwFatp,
                                '               ldblVKwFatp, ldblQKwFatfp, ldblVKwFatfp, ldblQKwhDevp, ldblVKwhDevp,
                                '               ldblQKwhDevfp, ldblVKwhDevfp, ldblQKwhUtrp, ldblVKwhUtrp, ldblQKwhUtrfp, ldblVKwhUtrfp, ldblQKwFat, ldblVKwFat,
                                '               ldblQKwFatp, ldblVKwFatp, ldblQKwFatfp, ldblVKwFatfp, ldblQKwFatUp, ldblVKwFatUp,
                                '               ldblQKwFatUp, ldblVKwFatUp, ldblQKwFatUp, ldblVKwFatUp, ldblVkwDscProv, ldblVkwDscReal,
                                '               ldblVkwhDevCcee, ldblVkwhCobCcee, ldblConvenios, ldblDiversos, ldblTaxados, ldblDevolucao,
                                '               0, ldblRetencao, ldblTip, ldblJuros, dvalor_diferenca_ece, dvalor_ece, ldblMust, ldblIcms1, ldblPis, ldblCofins,
                                '               ldblValorTot, dvalor_liquido, ldblQKwContr, ldblQKwContrp, ldblQKwContrfp, dqtde_fx1, dqtde_fx2, dqtde_fx3,
                                '               dqtde_fx4, dvlr_fx1, dvlr_fx2, dvlr_fx3, dvlr_fx4, dkwh_lido, lstrFase,
                                '               dbase_icms_1, daliquota_icms_1, dvalor_icms_1, dbase_icms_2, daliquota_icms_2,
                                '               dvalor_icms_2, ldblBasePis, dAliquota_PIS, ldblBaseCofins, dAliquota_COFINS, dreceitas_financeiras,
                                '               dressarcimento_idqual, dvalor_encargo_uso_sis_trans, ddesconto_must,
                                '               dencargo_kwh_faturado_ponta, dencargo_valor_kwh_faturado_ponta, dencargo_kwh_faturado_fora_ponta,
                                '               dencargo_valor_kwh_faturado_fora_ponta, dmwh_medio, dmwh_medio_horas, 0,
                                '               dVALOR_REVERSO, dVALOR_REVERSO_BAN, dREVERSO_PONTA, dREVERSO_PONTA_BANDEIRA,
                                '               dREVERSO_FORA_PONTA, dREVERSO_FORA_DE_PONTA_BANDEIRA, dbandeira_vlr_kwh_fat,
                                '               dbandeira_valor_kwh_fat_ponta, dbandeira_valor_kwh_fat_fora_ponta,
                                '               dvalor_energia_desconto_provisorio, dvalor_energia_desconto_realizado, dvalor_energia_devolucao_diferenca_ccee,
                                '               dvalor_energia_cobranca_diferenca_ccee, dCONSUMO_PONTA, dCONSUMO_FORA_PONTA, dREVERSO_FORA_PONTA,
                                '               dREVERSO_RESIDUO_FORA_PONTA, dTUSD, dCONSUMO_MEDIDO, dREVERSO_LIDO,
                                '               lstrFlgSt, ddatast, ddata_pagamento, 0)
                                'Else

                                If lintContInsertPri > 300 Then
                                    lstrSqlPri = lstrSqlPri & Microsoft.VisualBasic.Left(lstrSqlPAx, Len(lstrSqlPAx) - 2)
                                    objTempEstatis.TABLE = lstrSqlPri
                                    repositorioTempEstatis.Execute_2(objTempEstatis)

                                    lstrSqlPri = ""

                                    If CriaTabelas(lstrSqlPri, lstrSqlIte, False, True, False) Then
                                        lstrSqlPAx = ""
                                        lintContInsertPri = 1
                                    End If

                                End If
                            End If

                            'End If

                            BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 1)

                            System.Windows.Forms.Application.DoEvents()

                        Next

                        If bPlan = True Then

                            ExcelPlanilha.SaveAs(txtArq.Text)
                            ExcelPasta.Close()
                            ExcelAPP.Quit()

                            MessageBox.Show("Planilha gerada com sucesso !", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information)

                        Else

                            If lintContInsertItens > 0 And Len(Trim(lstrSqlIAx)) > 0 Then
                                lstrSqlIte = lstrSqlIte & Microsoft.VisualBasic.Left(lstrSqlIAx, Len(lstrSqlIAx) - 2)
                                objTempEstatisItens.TABLE = lstrSqlIte
                                repositorioTempEstatisItens.Execute_2(objTempEstatisItens)
                            End If

                            If lintContInsertPri > 0 And Len(Trim(lstrSqlPAx)) > 0 Then
                                lstrSqlPri = lstrSqlPri & Microsoft.VisualBasic.Left(lstrSqlPAx, Len(lstrSqlPAx) - 2)
                                objTempEstatis.TABLE = lstrSqlPri
                                repositorioTempEstatis.Execute_2(objTempEstatis)
                            End If

                        End If

                        lblnRetorno = True

                    End If 'Criatabelas

                Else
                    MessageBox.Show("Não existem faturas no período selecionado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    lblnRetorno = False
                    ' End If

                End If

                ' *********************************************************** NFTRANSICAO ****************************************************************
            ElseIf istrTabNf = "NFTRANSICAO" Then

                If Me.chkRen863_2019.CheckState = System.Windows.Forms.CheckState.Checked Then
                    lstrFiltro = lstrFiltro & " AND ( (NFTRANSICAO.ANOMES_FAT >= '" & Me.txtAno.Text & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) & "'"
                    lstrFiltro = lstrFiltro & " AND  NFTRANSICAO.ANOMES_FAT <= '" & Me.txtAno.Text & VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex) & "' )"
                Else
                    lstrFiltro = lstrFiltro & " AND ( (NFTRANSICAO.MESANO_REF >= '" & Me.txtAno.Text & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) & "'"
                    lstrFiltro = lstrFiltro & " AND NFTRANSICAO.MESANO_REF <= '" & Me.txtAno.Text & VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex) & "' )"
                End If

                lstrFiltro = lstrFiltro & " OR ( "
                lstrFiltro = lstrFiltro & "   NFTRANSICAO.FLGST = 'C' AND "
                lstrFiltro = lstrFiltro & "   NFTRANSICAO.MESANO_REF <> DATE_FORMAT(DATAST,'%Y%M') AND "
                lstrFiltro = lstrFiltro & "   NFTRANSICAO.DATAST >= DATE_FORMAT('" & CDate(ldteIni) & "','%Y%M%D') AND NFTRANSICAO.DATAST <= DATE_FORMAT('" & CDate(ldteFim) & "','%Y%M%D') "
                lstrFiltro = lstrFiltro & "  )"
                lstrFiltro = lstrFiltro & " )"

                If lstrFilPref <> "" Then
                    lstrFiltro = lstrFiltro & " And NFTRANSICAO.ROTA_QUATRO >= '" & Microsoft.VisualBasic.Left(lstrFilPref, 2) & Microsoft.VisualBasic.Right(VB6.GetItemString(Me.cmbRotaIni, Me.cmbRotaIni.SelectedIndex), 2) & "'"
                    lstrFiltro = lstrFiltro & " AND NFTRANSICAO.ROTA_QUATRO <= '" & Microsoft.VisualBasic.Right(lstrFilPref, 2) & Microsoft.VisualBasic.Right(VB6.GetItemString(Me.cmbRotaFim, Me.cmbRotaFim.SelectedIndex), 2) & "'"
                Else
                    lstrFiltro = lstrFiltro & " AND NFTRANSICAO.CADERNO  >= '" & Convert.ToInt32(VB6.GetItemString(Me.cmbRotaIni, Me.cmbRotaIni.SelectedIndex)) & "'"
                    lstrFiltro = lstrFiltro & " AND NFTRANSICAO.CADERNO  <= '" & Convert.ToInt32(VB6.GetItemString(Me.cmbRotaFim, Me.cmbRotaFim.SelectedIndex)) & "'"
                End If

                If Len(Trim(astrFiltro_Zona)) > 0 Then
                    objNf.ZONA = astrFiltro_Zona
                    lstrFiltro = lstrFiltro & " AND NFTRANSICAO.ZONA in( " & astrFiltro_Zona & ")"
                End If

                'Filtra caso somente um grupo tenha sido checado
                If Me.chkGrupoA.CheckState = System.Windows.Forms.CheckState.Checked And Not Me.chkGrupoB.CheckState = System.Windows.Forms.CheckState.Checked Then
                    objNf.GRUPO = "A"
                    lstrFiltro = lstrFiltro & " AND NFTRANSICAO.GRUPO = 'A'"
                ElseIf Me.chkGrupoB.CheckState = System.Windows.Forms.CheckState.Checked And Not Me.chkGrupoA.CheckState = System.Windows.Forms.CheckState.Checked Then
                    objNf.GRUPO = "B"
                    lstrFiltro = lstrFiltro & " AND NFTRANSICAO.GRUPO = 'B'"
                End If

                If Me.chkSomenteMiicrogeradoras.CheckState = System.Windows.Forms.CheckState.Checked Then
                    objNf.MICRO_GERACAO = 1
                    objNf.MICRO_GERACAO_DISTRIBUIDA = 1
                    lstrFiltro = lstrFiltro & " AND (NFTRANSICAO.MICRO_GERACAO = 1"
                    lstrFiltro = lstrFiltro & " OR NFTRANSICAO.MICRO_GERACAO_DISTRIBUIDA = 1)"
                    If Me.opbSomenteMGSefaz.Checked Then
                        lstrFiltro = lstrFiltro & " AND NFTRANSICAO.MICRO_GERACAO_CONVENIO_SEFAZ = 1"
                        objNf.MICRO_GERACAO_CONVENIO_SEFAZ = 1
                    ElseIf Me.opbSomenteMGNaoSefaz.Checked Then
                        lstrFiltro = lstrFiltro & " AND NFTRANSICAO.MICRO_GERACAO_CONVENIO_SEFAZ = 0"
                        objNf.MICRO_GERACAO_CONVENIO_SEFAZ = 0
                    End If
                End If


                If Me.opbRegiaoUrbano.Checked Then
                    objNf.REGIAO = "U"
                    lstrFiltro = lstrFiltro & " AND NFTRANSICAO.REGIAO = 'U'"
                ElseIf Me.opbRegiaoRural.Checked Then
                    objNf.REGIAO = "R"
                    lstrFiltro = lstrFiltro & " AND NFTRANSICAO.REGIAO = 'R'"
                End If

                If Me.chkFatComplementar.CheckState = System.Windows.Forms.CheckState.Checked Then
                    lstrFiltro = lstrFiltro & " AND NFTRANSICAO.FATURA_COMPLEMENTAR > 0"
                    objNf.FATURA_COMPLEMENTAR = 1
                Else
                    lstrFiltro = lstrFiltro & " AND NFTRANSICAO.FATURA_COMPLEMENTAR = 0"
                    objNf.FATURA_COMPLEMENTAR = 0
                End If

                lstrFiltro = lstrFiltro & " AND NFTRANSICAO.ITENSSERV IS NOT NULL"

                If cmbTipo.SelectedIndex = 1 Then
                    lstrFiltro = lstrFiltro & " AND CONSUM.MATRICULA > 0"
                ElseIf cmbTipo.SelectedIndex = 2 Then
                    lstrFiltro = lstrFiltro & " AND CONSUM.MATRICULA <= 0"
                End If

                lstrFiltro = lstrFiltro & MontaFiltroDataLeitura("NFTRANSICAO")

                objExecAtualizaBancoDados.QUERY_NAME = fRetornaView_Recebimentos(lstrFiltro, "NFTRANSICAO", False)
                'objExecAtualizaBancoDados.QUERY_NAME = fRetornaView(lstrFiltro, "NFTRANSICAO")
                dt = repositorioAtualizaBancoDados.Consultar(objExecAtualizaBancoDados)

                If dt.Rows.Count > 0 Then

                    BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 0, dt.Rows.Count)

                    If CriaTabelas(lstrSqlPri, lstrSqlIte, True, True, True) Then
                        lstrSqlIAx = ""
                        lstrSqlPAx = ""
                        lintContInsertPri = 1
                        lintContInsertItens = 1

                        'For Each objNfTransicaoFor As entidadeNfTransicao In vlist
                        For Each row As DataRow In dt.Rows

                            'Busca a matricula do socios caso seja nula ou em branco sempre sera ZERO
                            lblnControl = True

                            dvalor_juros_ece = Trim(IIf(IsDBNull(row.Item("valor_juros_ece")), 0, row.Item("valor_juros_ece")))
                            dvalor_ece = Trim(IIf(IsDBNull(row.Item("valor_ece")), 0, row.Item("valor_ece")))
                            dvalor_liquido = Trim(IIf(IsDBNull(row.Item("valor_liquido")), 0, row.Item("valor_liquido")))
                            dqtde_fx1 = Trim(IIf(IsDBNull(row.Item("qtde_fx1")), 0, row.Item("qtde_fx1")))
                            dqtde_fx2 = Trim(IIf(IsDBNull(row.Item("qtde_fx2")), 0, row.Item("qtde_fx2")))
                            dqtde_fx3 = Trim(IIf(IsDBNull(row.Item("qtde_fx3")), 0, row.Item("qtde_fx3")))
                            dqtde_fx4 = Trim(IIf(IsDBNull(row.Item("qtde_fx4")), 0, row.Item("qtde_fx4")))
                            dvlr_fx1 = Trim(IIf(IsDBNull(row.Item("vlr_fx1")), 0, row.Item("vlr_fx1")))
                            dvlr_fx2 = Trim(IIf(IsDBNull(row.Item("vlr_fx2")), 0, row.Item("vlr_fx2")))
                            dvlr_fx3 = Trim(IIf(IsDBNull(row.Item("vlr_fx3")), 0, row.Item("vlr_fx3")))
                            dvlr_fx4 = Trim(IIf(IsDBNull(row.Item("vlr_fx4")), 0, row.Item("vlr_fx4")))
                            dkwh_lido = Trim(IIf(IsDBNull(row.Item("kwh_lido")), 0, row.Item("kwh_lido")))
                            dbase_icms_1 = Trim(IIf(IsDBNull(row.Item("base_icms_1")), 0, row.Item("base_icms_1")))
                            daliquota_icms_1 = Trim(IIf(IsDBNull(row.Item("aliquota_icms_1")), 0, row.Item("aliquota_icms_1")))
                            dvalor_icms_1 = Trim(IIf(IsDBNull(row.Item("valor_icms_1")), 0, row.Item("valor_icms_1")))
                            dbase_icms_2 = Trim(IIf(IsDBNull(row.Item("base_icms_2")), 0, row.Item("base_icms_2")))
                            daliquota_icms_2 = Trim(IIf(IsDBNull(row.Item("aliquota_icms_2")), 0, row.Item("aliquota_icms_2")))
                            dvalor_icms_2 = Trim(IIf(IsDBNull(row.Item("valor_icms_2")), 0, row.Item("valor_icms_2")))
                            dAliquota_PIS = Trim(IIf(IsDBNull(row.Item("Aliquota_PIS")), 0, row.Item("Aliquota_PIS")))
                            dAliquota_COFINS = Trim(IIf(IsDBNull(row.Item("Aliquota_COFINS")), 0, row.Item("Aliquota_COFINS")))
                            dreceitas_financeiras = Trim(IIf(IsDBNull(row.Item("receitas_financeiras")), 0, row.Item("receitas_financeiras")))
                            dressarcimento_idqual = Trim(IIf(IsDBNull(row.Item("ressarcimento_idqual")), 0, row.Item("ressarcimento_idqual")))
                            dvalor_encargo_uso_sis_trans = Trim(IIf(IsDBNull(row.Item("valor_encargo_uso_sis_trans")), 0, row.Item("valor_encargo_uso_sis_trans")))
                            ddesconto_must = Trim(IIf(IsDBNull(row.Item("desconto_must")), 0, row.Item("desconto_must")))
                            dencargo_kwh_faturado_ponta = Trim(IIf(IsDBNull(row.Item("encargo_kwh_faturado_ponta")), 0, row.Item("encargo_kwh_faturado_ponta")))
                            dencargo_valor_kwh_faturado_ponta = Trim(IIf(IsDBNull(row.Item("encargo_valor_kwh_faturado_ponta")), 0, row.Item("encargo_valor_kwh_faturado_ponta")))
                            dencargo_kwh_faturado_fora_ponta = Trim(IIf(IsDBNull(row.Item("encargo_kwh_faturado_fora_ponta")), 0, row.Item("encargo_kwh_faturado_fora_ponta")))
                            dencargo_valor_kwh_faturado_fora_ponta = Trim(IIf(IsDBNull(row.Item("encargo_valor_kwh_faturado_fora_ponta")), 0, row.Item("encargo_valor_kwh_faturado_fora_ponta")))
                            dmwh_medio = Trim(IIf(IsDBNull(row.Item("mwh_medio")), 0, row.Item("mwh_medio")))
                            dmwh_medio_horas = Trim(IIf(IsDBNull(row.Item("mwh_medio_horas")), 0, row.Item("mwh_medio_horas")))
                            dVALOR_REVERSO = Trim(IIf(IsDBNull(row.Item("VALOR REVERSO")), 0, row.Item("VALOR REVERSO")))
                            dVALOR_REVERSO_BAN = Trim(IIf(IsDBNull(row.Item("VALOR REVERSO BAN")), 0, row.Item("VALOR REVERSO BAN")))
                            dREVERSO_PONTA = Trim(IIf(IsDBNull(row.Item("REVERSO PONTA")), 0, row.Item("REVERSO PONTA")))
                            dREVERSO_PONTA_BANDEIRA = Trim(IIf(IsDBNull(row.Item("REVERSO PONTA BANDEIRA")), 0, row.Item("REVERSO PONTA BANDEIRA")))
                            dREVERSO_FORA_DE_PONTA = Trim(IIf(IsDBNull(row.Item("REVERSO FORA DE PONTA")), 0, row.Item("REVERSO FORA DE PONTA")))
                            dREVERSO_FORA_DE_PONTA_BANDEIRA = Trim(IIf(IsDBNull(row.Item("REVERSO FORA DE PONTA BANDEIRA")), 0, row.Item("REVERSO FORA DE PONTA BANDEIRA")))
                            dbandeira_vlr_kwh_fat = Trim(IIf(IsDBNull(row.Item("bandeira_vlr_kwh_fat")), 0, row.Item("bandeira_vlr_kwh_fat")))
                            dbandeira_valor_kwh_fat_ponta = Trim(IIf(IsDBNull(row.Item("bandeira_valor_kwh_fat_ponta")), 0, row.Item("bandeira_valor_kwh_fat_ponta")))
                            dbandeira_valor_kwh_fat_fora_ponta = Trim(IIf(IsDBNull(row.Item("bandeira_valor_kwh_fat_fora_ponta")), 0, row.Item("bandeira_valor_kwh_fat_fora_ponta")))
                            dvalor_energia_desconto_provisorio = Trim(IIf(IsDBNull(row.Item("valor_energia_desconto_provisorio")), 0, row.Item("valor_energia_desconto_provisorio")))
                            dvalor_energia_desconto_realizado = Trim(IIf(IsDBNull(row.Item("valor_energia_desconto_realizado")), 0, row.Item("valor_energia_desconto_realizado")))
                            dvalor_energia_devolucao_diferenca_ccee = Trim(IIf(IsDBNull(row.Item("valor_energia_devolucao_diferenca_ccee")), 0, row.Item("valor_energia_devolucao_diferenca_ccee")))
                            dvalor_energia_cobranca_diferenca_ccee = Trim(IIf(IsDBNull(row.Item("valor_energia_cobranca_diferenca_ccee")), 0, row.Item("valor_energia_cobranca_diferenca_ccee")))
                            dCONSUMO_PONTA = Trim(IIf(IsDBNull(row.Item("CONSUMO_PONTA")), 0, row.Item("CONSUMO_PONTA")))
                            dCONSUMO_FORA_PONTA = Trim(IIf(IsDBNull(row.Item("CONSUMO_FORA_PONTA")), 0, row.Item("CONSUMO_FORA_PONTA")))
                            dREVERSO_FORA_PONTA = Trim(IIf(IsDBNull(row.Item("REVERSO_FORA_PONTA")), 0, row.Item("REVERSO_FORA_PONTA")))
                            dREVERSO_RESIDUO_FORA_PONTA = Trim(IIf(IsDBNull(row.Item("REVERSO_RESIDUO_FORA_PONTA")), 0, row.Item("REVERSO_RESIDUO_FORA_PONTA")))
                            dTUSD = Trim(IIf(IsDBNull(row.Item("TUSD")), 0, row.Item("TUSD")))
                            dCONSUMO_MEDIDO = Trim(IIf(IsDBNull(row.Item("CONSUMO_MEDIDO")), 0, row.Item("CONSUMO_MEDIDO")))
                            dREVERSO_LIDO = Trim(IIf(IsDBNull(row.Item("REVERSO_LIDO")), 0, row.Item("REVERSO_LIDO")))
                            ddatast = Trim(IIf(IsDBNull(row.Item("datast")), "1900-01-01", row.Item("datast")))
                            ddata_pagamento = Trim(IIf(IsDBNull(row.Item("data_pagamento")), "1900-01-01", row.Item("data_pagamento")))

                            sGrupo_tarifario = Trim(IIf(IsDBNull(row.Item("grupo_tarifario")), "", row.Item("grupo_tarifario")))
                            sClasse_faturada = Trim(IIf(IsDBNull(row.Item("classe_faturada")), "", row.Item("classe_faturada")))
                            sDescricao_classe = "" 'Trim(IIf(IsDBNull(row.Item("descricao_classe")), "", row.Item("descricao_classe")))
                            sMesano_referencia = Trim(IIf(IsDBNull(row.Item("mesano_referencia")), "", row.Item("mesano_referencia")))
                            sAnomes_fat = Trim(IIf(IsDBNull(row.Item("anomes_fat")), "", row.Item("anomes_fat")))
                            dData_vencimento = CDate(Trim(IIf(IsDBNull(row.Item("data_vencimento")), "1900-01-01", row.Item("data_vencimento"))))
                            dData_leitura_atual = CDate(Trim(IIf(IsDBNull(row.Item("data_leitura_atual")), "1900-01-01", row.Item("data_leitura_atual"))))
                            dData_leitura_anterior = CDate(Trim(IIf(IsDBNull(row.Item("data_leitura_anterior")), "1900-01-01", row.Item("data_leitura_anterior"))))
                            dNumNf = CInt(IIf(IsDBNull(row.Item("numero_fatura")), 0, row.Item("numero_fatura")))
                            llngMatricula = CInt(IIf(IsDBNull(row.Item("MATRICULA")), 0, row.Item("MATRICULA")))
                            lstrFlgSt = Trim(IIf(IsDBNull(row.Item("FLGST")), "", row.Item("FLGST")))
                            ldteFlgSt = CDate(IIf(IsDBNull(row.Item("DATAST")), "1900-01-01", row.Item("DATAST")))
                            lstrMesAno = IIf(IsDBNull(row.Item("MESANO")), "01/1900", row.Item("MESANO"))

                            'If lstrFlgSt = "C" Then
                            '    If ldteFlgSt >= CDate("01/" & lstrMesAno) And ldteFlgSt <= CDate(UltimoDiaMes(Microsoft.VisualBasic.Left(lstrMesAno, 2), Microsoft.VisualBasic.Right(lstrMesAno, 4)) & "/" & lstrMesAno) Then
                            '        lblnControl = False
                            '    Else
                            '        lblnControl = True
                            '    End If
                            'End If

                            If istrSocios = "1" Then
                                If Me.cmbSocios.SelectedIndex = 1 Then 'Somente Socios
                                    lblnControl = (llngMatricula > 0)
                                ElseIf Me.cmbSocios.SelectedIndex = 2 Then  'Somente não socios
                                    lblnControl = (llngMatricula = 0)
                                End If
                            End If

                            If lblnControl = True Then

                                lstrItens = IIf(IsDBNull(row.Item("ITENSSERV")), "", row.Item("ITENSSERV"))
                                lstrClasse = IIf(IsDBNull(row.Item("codigo_classe")), "0000", row.Item("codigo_classe"))
                                lstrZona = IIf(IsDBNull(row.Item("ZONA")), "000", row.Item("ZONA"))
                                lstrLivro = IIf(IsDBNull(row.Item("LIVRO")), "00", row.Item("LIVRO"))
                                lstrConta = IIf(IsDBNull(row.Item("CONTA")), "000000", row.Item("CONTA"))
                                llngUnidId = CInt(IIf(IsDBNull(row.Item("UNID_ID")), 0, row.Item("UNID_ID")))
                                llngConsId = CInt(IIf(IsDBNull(row.Item("CONS_ID")), 0, row.Item("CONS_ID")))
                                lstrGrupo = Mid(IIf(IsDBNull(row.Item("TA")), "01B1", row.Item("TA")), 3, 2)
                                lstrNome = BuscaNome(llngConsId, llngUnidId, Microsoft.VisualBasic.Left(lstrGrupo, 1))
                                lintLivreEspecial = IIf(IsDBNull(row.Item("LIVREESPECIAL")), 0, row.Item("LIVREESPECIAL"))
                                lintLivreVerde = IIf(IsDBNull(row.Item("LIVRE_VERDE")), 0, row.Item("LIVRE_VERDE"))
                                lintParcialmenteCativo = IIf(IsDBNull(row.Item("PARCIALMENTE_CATIVO")), 0, row.Item("PARCIALMENTE_CATIVO"))
                                lstrFase = IIf(IsDBNull(row.Item("FASE")), "M", row.Item("FASE"))
                                lstrFlgSt = Trim(IIf(IsDBNull(row.Item("FLGST")), "", row.Item("FLGST")))
                                ldteFlgSt = CDate(IIf(IsDBNull(row.Item("DATAST")), "1900-01-01", row.Item("DATAST")))
                                lstrFlgMedFat = Trim(IIf(IsDBNull(row.Item("FLGMEDFAT")), "", row.Item("FLGMEDFAT")))

                                Dim bFATURA_FINAL As Boolean = Trim(IIf(IsDBNull(row.Item("FATURA_FINAL")), 0, row.Item("FATURA_FINAL")))
                                lintFaturaFinal = IIf(bFATURA_FINAL, 1, 0)

                                Dim bIRRIGACAO_AQUICULTURA As Boolean = Trim(IIf(IsDBNull(row.Item("IRRIGACAO_AQUICULTURA")), 0, row.Item("IRRIGACAO_AQUICULTURA")))
                                lintIrrigacaoAquicultura = IIf(bIRRIGACAO_AQUICULTURA, 1, 0)

                                Dim bMICRO_GERACAO_CONVENIO_SEFAZ As Boolean = Trim(IIf(IsDBNull(row.Item("MICRO_GERACAO_CONVENIO_SEFAZ")), 0, row.Item("MICRO_GERACAO_CONVENIO_SEFAZ")))
                                lintFaturaFinal = IIf(bFATURA_FINAL, 1, 0)

                                Dim bMICRO_GERACAO As Boolean = Trim(IIf(IsDBNull(row.Item("MICRO_GERACAO")), 0, row.Item("MICRO_GERACAO")))
                                lintMicroGeracao = IIf(bMICRO_GERACAO, 1, 0)

                                Dim bMICRO_GERACAO_DISTRIBUIDA As Boolean = Trim(IIf(IsDBNull(row.Item("MICRO_GERACAO_DISTRIBUIDA")), 0, row.Item("MICRO_GERACAO_DISTRIBUIDA")))
                                lintMicroGeracaoDistribuida = IIf(bMICRO_GERACAO_DISTRIBUIDA, 1, 0)

                                Dim bTARIFA_BRANCA As Boolean = Trim(IIf(IsDBNull(row.Item("TARIFA_BRANCA")), 0, row.Item("TARIFA_BRANCA")))
                                lintTarifaBranca = IIf(bTARIFA_BRANCA, 1, 0)

                                'If lstrFlgSt = "C" Then
                                '    If ldteFlgSt <= ldteFim Then
                                '        lintMpr = -1
                                '    Else
                                '        lintMpr = 1
                                '    End If
                                'Else
                                lintMpr = 1
                                'End If

                                ldblValorTot = IIf(IsDBNull(row.Item("valor_total")), 0, row.Item("valor_total")) * lintMpr
                                lstrGrupoT = Microsoft.VisualBasic.Left(lstrGrupo, IIf(Microsoft.VisualBasic.Left(lstrGrupo, 1) = "B", 1, 2))

                                If lstrGrupoT = "A4" Then
                                    lstrGrupoT = "B"
                                End If

                                '
                                If lstrGrupo = "A4" Then iblnTar_A4 = True
                                If lstrGrupo = "AA" Then iblnTar_AA = True
                                If lstrGrupo = "AL" Then iblnTar_AL = True
                                If lstrGrupo = "AS" Then iblnTar_AS = True
                                If lstrGrupo = "AV" Then iblnTar_AV = True
                                If lstrGrupo = "AX" Then iblnTar_AX = True
                                If iblnTar_B = False And Microsoft.VisualBasic.Left(lstrGrupo, 1) = "B" Then iblnTar_B = True
                                '

                                'Convencional
                                'Quantidade
                                ldblQKwhCons = 0 'Consumo lido
                                ldblQKwhFat = 0 'Consumo faturado
                                ldblQKwhFatBan = 0 'Consumo Faturado Bandeira
                                ldblVKwhFatBan = 0 'Consumo faturado bandeira
                                ldblQKwhFatTU = 0 'Consumo faturado TUSD
                                ldblQkWhFatTE = 0 'Consumo faturado TE
                                ldblQkWhFatTEBan = 0 'Consumo faturado TE bandeira
                                'ldblQKwhReverso = 0  'Consumo reverso
                                ldblQKwContr = 0 'Demanda Contratada
                                ldblQKwFat = 0 'Demanda

                                'Valor
                                ldblVKwhCons = 0 'Consumo lido
                                ldblVKwhFat = 0 'Consumo faturado
                                ldblVKwhFatBan = 0 'Consumo faturado Bandeira
                                ldblVkWhFatTU = 0 'Consumo faturado TUSD
                                ldblVkWhFatTE = 0 'Consumo faturado TE
                                ldblVkWhFatTEBan = 0 'Consumo faturado TE bandeira
                                'ldblVKwhReverso = 0  'Consumo reverso
                                ldblVKwFat = 0 'Demanda
                                '

                                'Horosazonal
                                'Quantidade
                                ldblQKwhFatp = 0 'Qtde Consumo faturado p
                                ldblQKwhFati = 0 'Qtde Consumo faturado i
                                ldblQKwhFatfp = 0 'Qtde Consumo faturado fp
                                ldblQKwhFatpBan = 0 'Qtde Consumo faturado p Bandeira
                                ldblQKwhFatiBan = 0 'Qtde Consumo faturado i Bandeira
                                ldblQKwhFatfpBan = 0 'Qtde Consumo faturado fp Bandeira
                                ldblQKwhFatpLiv = 0 'Qtde Consumo faturado p Livre
                                ldblQKwhFatfpLiv = 0 'Qtde Consumo faturado fp Livre						
                                '
                                ldblQKwhDevp = 0 'Qtde Consumo Devolvido p
                                ldblQKwhDevfp = 0 'Qtde Consumo Devolvido fp
                                ldblQKwhUtrp = 0 'Qtde Consumo Ultrapassado p
                                ldblQKwhUtrfp = 0 'Qtde Consumo Ultrapassado fp
                                '							
                                ldblQKwContrp = 0 'Qtde Demanda Contratada p
                                ldblQKwContrfp = 0 'Qtde Demanda Contratada fp
                                ldblQKwFatp = 0 'Qtde Demanda p
                                ldblQKwFatfp = 0 'Qtde Demanda fp
                                ldblQKwDifFatp = 0 'Qtde Dif. Demanda p
                                ldblQKwDifFatfp = 0 'Qtde Dif. Demanda fp
                                ldblQKwFatUp = 0 'Qtde Demanda de ultrapassagem p
                                ldblQKwFatUfp = 0 'Qtde Demanda de ultrapassagem fp
                                ldblQKwhReversop = 0 'Qtde consumo reverso p
                                ldblQKwhReversoi = 0 'Qtde consumo reverso i
                                ldblQKwhReversofp = 0 'Qtde consumo reverso fp
                                ldblQKwhReversop_sefaz = 0 'Qtde consumo reverso p
                                ldblQKwhReversoi_sefaz = 0 'Qtde consumo reverso i
                                ldblQKwhReversofp_sefaz = 0 'Qtde consumo reverso fp

                                'Valor
                                ldblVKwhFatp = 0 'Valor Consumo faturado p
                                ldblVKwhFati = 0 'Valor Consumo faturado i
                                ldblVKwhFatfp = 0 'Valor Consumo faturado fp
                                ldblVKwhFatpBan = 0 'Valor Consumo faturado p Bandeira
                                ldblVKwhFatiBan = 0 'Valor Consumo faturado i Bandeira
                                ldblVKwhFatfpBan = 0 'Valor Consumo faturado fp Bandeira
                                ldblVKwhFatpLiv = 0 'Valor Consumo faturado p Livre
                                ldblVKwhFatfpLiv = 0 'Valor Consumo faturado fp Livre
                                '
                                ldblVKwhDevp = 0 'Valor Consumo devolvido p
                                ldblVKwhDevfp = 0 'Valor Consumo devolvido fp
                                ldblVKwhUtrp = 0 'Valor Consumo Ultrapassado p
                                ldblVKwhUtrfp = 0 'Valor Consumo Ultrapassado fp
                                '
                                ldblVKwFatp = 0 'Valor Demanda p
                                ldblVKwFatfp = 0 'Valor Demanda fp
                                ldblVKwDifFatp = 0 'Valor Dif. Demanda p
                                ldblVKwDifFatfp = 0 'Valor Dif. Demanda fp
                                ldblVKwFatUp = 0 'Valor Demanda de ultrapassagem p
                                ldblVKwFatUfp = 0 'Valor Demanda de ultrapassagem fp

                                ldblVKwhReversoCompTEQtde = 0
                                ldblVKwhReversoCompTUSDQtde = 0

                                ldblVKwhReversoCompTEVlr = 0
                                ldblVKwhReversoCompTUSDVlr = 0
                                '
                                ldblVKwhReversop = 0 'valor consumo reverso p
                                ldblVKwhReversoi = 0 'valor consumo reverso i
                                ldblVKwhReversofp = 0 'valor consumo reverso fp

                                ldblVKwhReversop_sefaz = 0 'valor consumo reverso p
                                ldblVKwhReversoi_sefaz = 0 'valor consumo reverso i
                                ldblVKwhReversofp_sefaz = 0 'valor consumo reverso fp

                                'Desconto Provisorio
                                ldblVkwDscProv = 0 'Desconto provisorio
                                ldblVkwDscReal = 0 'Desconto real
                                ldblVkwDevCcee = 0 'Diferença a devolver
                                ldblVkwCobCcee = 0 'Diferença a cobrar			
                                '
                                ldblVkwhDscProv = 0 'Desconto provisorio
                                ldblVkwhDscReal = 0 'Desconto real
                                ldblVkwhDevCcee = 0 'Diferença a devolver
                                ldblVkwhCobCcee = 0 'Diferença a cobrar
                                '----
                                ldblTip = 0 'Vlr Iluminação Pública.
                                ldblIcms1 = 0 'Vlr Icms.
                                ldblIcms2 = 0 'Vlr Icms.
                                ldblPis = 0 'Vlr PIS.
                                ldblCofins = 0 'Vlr COFINS.
                                '
                                ldblIcmsSt = 0 'Vlr Icms Substituição Tributária
                                ldblPisSt = 0 'Vlr Pis Substituição Tributária
                                ldblCofinsSt = 0 'Vlr Cofins Substituição Tributária
                                '			
                                ldblBaseIcms1 = 0 'Vlr Base Icms.
                                ldblBaseIcms2 = 0 'Vlr Base Icms.
                                ldblBasePis = 0 'Vlr Base PIS.
                                ldblBaseCofins = 0 'Vlr Base COFINS.					
                                '
                                ldblIcmsPisCof = 0 'Vlr Icms/Pis/Cofins.
                                ldblSaldoArre = 0
                                ldblEncFinan = 0
                                ldblDifEltrbr = 0
                                ldblJuros = 0 'Juros verificar ainda com o calculo.
                                ldblEncargo = 0 'Encargos confirma ainda com o calculo
                                ldblMust = 0 'Valor de MUST
                                '	
                                ldblConsumoReativo = 0 'Consumo Reativo
                                ldblDemandaReativa = 0 'Demanda Reativo
                                ldblConsumoReativop = 0 'Consumo Reativo p
                                ldblConsumoReativofp = 0 'Consumo Reativo fp
                                ldblDemandaReativap = 0 'Demanda Reativo p
                                ldblDemandaReativafp = 0 'Demanda Reativo fp
                                ldblDiferenca = 0
                                '************

                                '************ COMEÇA A COSTURAR AQUI
                                ldblBaseIcms1 = IIf(IsDBNull(row.Item("base_icms_1")), 0, row.Item("base_icms_1")) * lintMpr
                                'ldblBaseIcms1 = ldblBaseIcms1 + BuscaVlrItem(lstrItens, "0302063035") * lintMpr 'Marreta por problemas de calculo na fatura 21 de 12/2019
                                ldblBaseIcms2 = IIf(IsDBNull(row.Item("base_icms_2")), 0, row.Item("base_icms_2")) * lintMpr
                                ldblBasePis = IIf(IsDBNull(row.Item("base_pis")), 0, row.Item("base_pis")) * lintMpr
                                ldblBaseCofins = IIf(IsDBNull(row.Item("base_cofins")), 0, row.Item("base_cofins")) * lintMpr
                                ldblDiferenca = IIf(IsDBNull(row.Item("dif.rel.rec")), 0, row.Item("dif.rel.rec"))

                                If lstrGrupo = "AS" Or lstrGrupo = "A4" Or Microsoft.VisualBasic.Left(lstrGrupo, 1) = "B" Then

                                    If Microsoft.VisualBasic.Left(lstrGrupo, 1) <> "B" Then

                                        ldblQKwhCons = IIf(IsDBNull(row.Item("valor_total")), 0, row.Item("valor_total")) * lintMpr 'Consumo lido
                                        ldblQKwhFat = IIf(IsDBNull(row.Item("kwh_faturado")), 0, row.Item("kwh_faturado")) * lintMpr 'Consumo faturado
                                        'ldblQKwhFatBan = IIf(IsDBNull(row.Item("base_cofins")), 0, row.Item("base_cofins")) * lintMpr 'Consumo faturado bandeira ***

                                        ldblVKwhCons = IIf(IsDBNull(row.Item("vlr_kwh_faturado")), 0, row.Item("vlr_kwh_faturado")) * lintMpr 'Consumo lido ***
                                        ldblVKwhFat = IIf(IsDBNull(row.Item("vlr_kwh_faturado")), 0, row.Item("vlr_kwh_faturado")) * lintMpr 'Consumo faturado
                                        ldblVKwhFatBan = IIf(IsDBNull(row.Item("bandeira_vlr_kwh_fat")), 0, row.Item("bandeira_vlr_kwh_fat")) * lintMpr 'Consumo faturado bandeira

                                    Else

                                        'Quantidade
                                        ldblQKwhCons = IIf(IsDBNull(row.Item("valor_total")), 0, row.Item("valor_total")) * lintMpr 'Consumo lido

                                        If lintTarifaBranca = 0 Then
                                            ldblQKwhFat = IIf(IsDBNull(row.Item("kwh_faturado")), 0, row.Item("kwh_faturado")) * lintMpr 'Consumo faturado kwh_faturado
                                            'ldblQKwhFatBan = IIf(IsDBNull(row.Item("kwh_lido")), 0, row.Item("kwh_lido")) * lintMpr 'Consumo faturado bandeira ***
                                        Else
                                            ldblQKwhFatp = IIf(IsDBNull(row.Item("kwh_faturado")), 0, row.Item("kwh_faturado")) * lintMpr 'Consumo faturado
                                        End If

                                        ldblQKwhFatTU = IIf(IsDBNull(row.Item("TUSD")), 0, row.Item("TUSD")) * lintMpr 'consumo faturado TUSD
                                        'ldblQkWhFatTE = BuscaVlrItem(lstrItens, "030401009") * lintMpr 'consumo faturado TE
                                        'ldblQkWhFatTEBan = BuscaVlrItem(lstrItens, "030411009") * lintMpr 'consumo faturado TE bandeira

                                        'Valor
                                        ldblVKwhCons = IIf(IsDBNull(row.Item("vlr_kwh_faturado")), 0, row.Item("vlr_kwh_faturado")) * lintMpr

                                        If lintTarifaBranca = 0 Then
                                            'ldblVKwhFat = (BuscaVlrItem(lstrItens, "030202009")) * lintMpr 'Consumo faturado ***
                                            'ldblVKwhFatBan = (BuscaVlrItem(lstrItens, "030212009")) * lintMpr 'Consumo faturado bandeira ***

                                            ldblVKwhFat = IIf(IsDBNull(row.Item("vlr_kwh_faturado")), 0, row.Item("vlr_kwh_faturado")) * lintMpr 'Consumo faturado
                                            'ldblVKwhFatBan = (BuscaVlrItem(lstrItens, "030212009")) * lintMpr 'Consumo faturado bandeira ***
                                        Else

                                            'ldblVKwhFatp = (BuscaVlrItem(lstrItens, "030202019")) * lintMpr 'Consumo faturado ** *
                                            'ldblVKwhFati = (BuscaVlrItem(lstrItens, "030202029")) * lintMpr 'Consumo faturado ***
                                            'ldblVKwhFatfp = (BuscaVlrItem(lstrItens, "030202039")) * lintMpr 'Consumo faturado ***
                                            'ldblVKwhFatpBan = (BuscaVlrItem(lstrItens, "030212019")) * lintMpr 'Consumo faturado bandeira ***
                                            'ldblVKwhFatiBan = (BuscaVlrItem(lstrItens, "030212029")) * lintMpr 'Consumo faturado bandeira ***
                                            'ldblVKwhFatfpBan = (BuscaVlrItem(lstrItens, "030212039")) * lintMpr 'Consumo faturado bandeira ***

                                        End If

                                        If lintMicroGeracao = 1 Or lintMicroGeracaoDistribuida = 1 Then

                                            If lintMicroGeracaoConvenioSefaz = 0 Then

                                                ldblVKwhReversoCompTEQtde = IIf(IsDBNull(row.Item("qtd_COMP. TE")), 0, row.Item("qtd_COMP. TE"))
                                                ldblVKwhReversoCompTUSDQtde = IIf(IsDBNull(row.Item("qtd_COMP. TUSD")), 0, row.Item("qtd_COMP. TUSD"))

                                                ldblVKwhReversoCompTEVlr = IIf(IsDBNull(row.Item("vlr_COMP. TE")), 0, row.Item("vlr_COMP. TE"))
                                                ldblVKwhReversoCompTUSDVlr = IIf(IsDBNull(row.Item("vlr_COMP. TUSD")), 0, row.Item("vlr_COMP. TUSD"))

                                                ldblQKwhReversop = (ldblVKwhReversoCompTEQtde + ldblVKwhReversoCompTUSDQtde) * lintMpr
                                                ldblVKwhReversop = (ldblVKwhReversoCompTEVlr + ldblVKwhReversoCompTUSDVlr) * lintMpr

                                                ldblVKwhReversofp = IIf(IsDBNull(row.Item("VALOR REVERSO")), 0, row.Item("VALOR REVERSO")) * lintMpr 'Valor Reverso ***

                                            Else

                                                ldblVKwhReversoCompTEQtde = IIf(IsDBNull(row.Item("qtd_COMP. TE")), 0, row.Item("qtd_COMP. TE"))
                                                ldblVKwhReversoCompTUSDQtde = IIf(IsDBNull(row.Item("qtd_COMP. TUSD")), 0, row.Item("qtd_COMP. TUSD"))

                                                ldblVKwhReversoCompTEVlr = IIf(IsDBNull(row.Item("vlr_COMP. TE")), 0, row.Item("vlr_COMP. TE"))
                                                ldblVKwhReversoCompTUSDVlr = IIf(IsDBNull(row.Item("vlr_COMP. TUSD")), 0, row.Item("vlr_COMP. TUSD"))

                                                ldblQKwhReversop_sefaz = (ldblVKwhReversoCompTEQtde + ldblVKwhReversoCompTUSDQtde) * lintMpr
                                                'ldblQKwhReversoi_sefaz = (ldblVKwhReversoCompTEVlr + ldblVKwhReversoCompTUSDVlr) * lintMpr

                                                ldblVKwhReversofp_sefaz = IIf(IsDBNull(row.Item("VALOR REVERSO")), 0, row.Item("VALOR REVERSO")) * lintMpr 'Valor Reverso

                                            End If

                                        End If

                                        If lintMicroGeracaoConvenioSefaz = 0 Then

                                            If ldblVKwhReversofp = 0 Then
                                                If ldblVkWhFatTU + ldblVkWhFatTE > 0 Then
                                                    ldblVKwhReversofp = (ldblVKwhFat - (ldblVkWhFatTU + ldblVkWhFatTE)) * lintMpr 'Valor Reverso
                                                    If ldblVKwhFat - (ldblVkWhFatTU + ldblVkWhFatTE) > 0 Then
                                                        ldblVKwhReversofp = ldblVKwhReversofp + (ldblVKwhFatBan - ldblVkWhFatTEBan)
                                                    End If
                                                End If
                                            End If

                                        Else

                                            If ldblVKwhReversofp_sefaz = 0 Then
                                                If ldblVkWhFatTU + ldblVkWhFatTE > 0 Then
                                                    ldblVKwhReversofp_sefaz = (ldblVKwhFat - (ldblVkWhFatTU + ldblVkWhFatTE)) * lintMpr 'Valor Reverso
                                                    If ldblVKwhFat - (ldblVkWhFatTU + ldblVkWhFatTE) > 0 Then
                                                        ldblVKwhReversofp_sefaz = ldblVKwhReversofp_sefaz + (ldblVKwhFatBan - ldblVkWhFatTEBan)
                                                    End If
                                                End If
                                            End If

                                        End If

                                    End If

                                    'Demanda
                                    ldblQKwContr = IIf(IsDBNull(row.Item("demanda_contratada_convencional")), 0, row.Item("demanda_contratada_convencional")) * lintMpr 'Demanda Contratada
                                    ldblQKwFat = IIf(IsDBNull(row.Item("kw_faturado")), 0, row.Item("kw_faturado")) * lintMpr 'Demanda
                                    ldblQKwFatUfp = IIf(IsDBNull(row.Item("kw_ultrapassado")), 0, row.Item("kw_ultrapassado")) * lintMpr 'Demanda de ultrapassagem fp

                                    'Valor
                                    ldblVKwFat = IIf(IsDBNull(row.Item("valor_kw_faturado")), 0, row.Item("valor_kw_faturado")) * lintMpr 'Demanda
                                    ldblVKwFatUfp = IIf(IsDBNull(row.Item("valor_kw_ultrapassado")), 0, row.Item("valor_kw_ultrapassado")) * lintMpr 'Demanda de ultrapassagem Convencional
                                    ldblConsumoReativo = IIf(IsDBNull(row.Item("valor_consumo_reativo")), 0, row.Item("valor_consumo_reativo")) * lintMpr 'Consumo Reativo
                                    ldblDemandaReativa = IIf(IsDBNull(row.Item("valor_demanda_reativo")), 0, row.Item("valor_demanda_reativo")) * lintMpr 'Demanda Reativo

                                ElseIf lstrGrupo = "AA" Or lstrGrupo = "AV" Or lstrGrupo = "AL" Or lstrGrupo = "AP" Or lstrGrupo = "AX" Then

                                    'Quantidade
                                    ldblQKwhFatp = 0
                                    ldblQKwhFatfp = 0
                                    ldblQKwhFatpLiv = 0
                                    ldblQKwhFatfpLiv = 0
                                    ldblQKwhFatpAUX = 0
                                    ldblQKwhFatfpAUX = 0


                                    'Micro Geração
                                    If lintMicroGeracaoConvenioSefaz = 0 Then

                                        ldblVKwhReversoCompTEQtde = IIf(IsDBNull(row.Item("qtd_COMP. TE")), 0, row.Item("qtd_COMP. TE"))
                                        ldblVKwhReversoCompTUSDQtde = IIf(IsDBNull(row.Item("qtd_COMP. TUSD")), 0, row.Item("qtd_COMP. TUSD"))

                                        ldblVKwhReversoCompTEVlr = IIf(IsDBNull(row.Item("vlr_COMP. TE")), 0, row.Item("vlr_COMP. TE"))
                                        ldblVKwhReversoCompTUSDVlr = IIf(IsDBNull(row.Item("vlr_COMP. TUSD")), 0, row.Item("vlr_COMP. TUSD"))

                                        ldblQKwhReversop = (ldblVKwhReversoCompTEQtde + ldblVKwhReversoCompTUSDQtde) * lintMpr
                                        ldblVKwhReversop = (ldblVKwhReversoCompTEVlr + ldblVKwhReversoCompTUSDVlr) * lintMpr

                                        'ldblQKwhReversop = BuscaVlrItem(lstrItens, "0302012010") * lintMpr 'Qtde Medido Reverso na ponta ***
                                        ldblQKwhReversofp = IIf(IsDBNull(row.Item("REVERSO_FORA_PONTA")), 0, row.Item("REVERSO_FORA_PONTA")) * lintMpr 'Qtde Medido Reverso fora ponta
                                    Else

                                        ldblVKwhReversoCompTEQtde = IIf(IsDBNull(row.Item("qtd_COMP. TE")), 0, row.Item("qtd_COMP. TE"))
                                        ldblVKwhReversoCompTUSDQtde = IIf(IsDBNull(row.Item("qtd_COMP. TUSD")), 0, row.Item("qtd_COMP. TUSD"))

                                        ldblVKwhReversoCompTEVlr = IIf(IsDBNull(row.Item("vlr_COMP. TE")), 0, row.Item("vlr_COMP. TE"))
                                        ldblVKwhReversoCompTUSDVlr = IIf(IsDBNull(row.Item("vlr_COMP. TUSD")), 0, row.Item("vlr_COMP. TUSD"))

                                        ldblQKwhReversop_sefaz = (ldblVKwhReversoCompTEQtde + ldblVKwhReversoCompTUSDQtde) * lintMpr
                                        ldblVKwhReversop_sefaz = (ldblVKwhReversoCompTEVlr + ldblVKwhReversoCompTUSDVlr) * lintMpr

                                        'ldblQKwhReversop_sefaz = BuscaVlrItem(lstrItens, "0302012010") * lintMpr 'Qtde Medido Reverso na ponta ***
                                        ldblQKwhReversofp_sefaz = IIf(IsDBNull(row.Item("REVERSO_FORA_PONTA")), 0, row.Item("REVERSO_FORA_PONTA")) * lintMpr 'Qtde Medido Reverso fora ponta
                                    End If

                                    'PLD
                                    ldblQKwhDevp = IIf(IsDBNull(row.Item("kwh_devolvido_ponta")), 0, row.Item("kwh_devolvido_ponta"))  'Consumo devolvido na p
                                    ldblQKwhDevfp = IIf(IsDBNull(row.Item("kwh_devolvido_fora_ponta")), 0, row.Item("kwh_devolvido_fora_ponta"))  'Consumo devolvido na fp
                                    If ldblQKwhDevp < 0 Then ldblQKwhDevp = ldblQKwhDevp * -1
                                    If ldblQKwhDevfp < 0 Then ldblQKwhDevfp = ldblQKwhDevfp * -1
                                    ldblQKwhDevp = ldblQKwhDevp * lintMpr 'Consumo devolvido na p
                                    ldblQKwhDevfp = ldblQKwhDevfp * lintMpr 'Consumo devolvido na fp
                                    ldblQKwhUtrp = IIf(IsDBNull(row.Item("kwh_ultrapassado_ponta")), 0, row.Item("kwh_ultrapassado_ponta")) * lintMpr 'Consumo ultrapassado na p
                                    ldblQKwhUtrfp = IIf(IsDBNull(row.Item("kwh_ultrapassado_fora_ponta")), 0, row.Item("kwh_ultrapassado_fora_ponta")) * lintMpr 'Consumo ultrapassado na fp

                                    If ldblQKwhFatp = 0 Then

                                        'ldblQKwhFatp = (BuscaVlrItem(lstrItens, "0302010010")) * lintMpr 'Consumo faturado p 
                                        ldblQKwhFatp = IIf(IsDBNull(row.Item("kwh_faturado_ponta")), 0, row.Item("kwh_faturado_ponta")) * lintMpr

                                        If lintMicroGeracaoConvenioSefaz = 0 Then
                                            If ldblQKwhFatp <= ldblQKwhReversop Then
                                                ldblQKwhReversop = ldblQKwhFatp
                                                ldblQKwhFatp = 0
                                            Else
                                                ldblQKwhFatp = ldblQKwhFatp - ldblQKwhReversop
                                            End If
                                        Else
                                            If ldblQKwhFatp <= ldblQKwhReversop_sefaz Then
                                                ldblQKwhReversop_sefaz = ldblQKwhFatp
                                                ldblQKwhFatp = 0
                                            Else
                                                ldblQKwhFatp = ldblQKwhFatp - ldblQKwhReversop_sefaz
                                            End If
                                        End If

                                        'ldblQKwhFatpBan = (BuscaVlrItem(lstrItens, "0302110010")) * lintMpr 'Consumo faturado p bandeira ****

                                        If ldblQKwhFatpBan > 0 Then
                                            If ldblQKwhFatpBan <= ldblQKwhFatpAUX Then
                                                ldblQKwhFatpBan = 0
                                            Else
                                                ldblQKwhFatpBan = ldblQKwhFatpBan - ldblQKwhFatpAUX
                                            End If
                                        End If

                                        If lstrGrupo = "AL" Then
                                            If lintParcialmenteCativo = 1 Then
                                                ldblQKwhFatpLiv = IIf(IsDBNull(row.Item("kwh_faturado_ponta")), 0, row.Item("kwh_faturado_ponta")) * lintMpr 'Consumo faturado p
                                                ldblQKwhFatp = ldblQKwhFatp - ldblQKwhFatpLiv
                                                'ldblQKwhFatpBan = ldblQKwhFatpBan - ldblQKwhFatpLiv
                                            Else
                                                ldblQKwhFatpLiv = IIf(IsDBNull(row.Item("kwh_faturado_ponta")), 0, row.Item("kwh_faturado_ponta")) * lintMpr 'Consumo faturado p
                                                ldblQKwhFatp = ldblQKwhFatp - ldblQKwhFatpLiv
                                                If ldblQKwhFatpBan >= 0 Then ldblQKwhFatpBan = 0
                                            End If
                                        End If

                                    End If

                                    If ldblQKwhFatfp = 0 Then

                                        ldblQKwhFatfp = IIf(IsDBNull(row.Item("kwh_faturado_fora_ponta")), 0, row.Item("kwh_faturado_fora_ponta")) * lintMpr 'Consumo faturado fp

                                        If lintMicroGeracaoConvenioSefaz = 0 Then
                                            If ldblQKwhFatfp <= ldblQKwhReversofp Then
                                                ldblQKwhReversofp = ldblQKwhFatfp
                                                ldblQKwhFatfp = 0
                                            Else
                                                ldblQKwhFatfp = ldblQKwhFatfp - ldblQKwhReversofp
                                            End If
                                        Else
                                            If ldblQKwhFatfp <= ldblQKwhReversofp_sefaz Then
                                                ldblQKwhReversofp_sefaz = ldblQKwhFatfp
                                                ldblQKwhFatfp = 0
                                            Else
                                                ldblQKwhFatfp = ldblQKwhFatfp - ldblQKwhReversofp_sefaz
                                            End If
                                        End If

                                        'ldblQKwhFatfpBan = (BuscaVlrItem(lstrItens, "0302110011")) * lintMpr 'Consumo faturado fp ****

                                        If ldblQKwhFatfpBan > 0 Then
                                            If ldblQKwhFatfpBan <= ldblQKwhFatfpAUX Then
                                                ldblQKwhFatfpBan = 0
                                            Else
                                                ldblQKwhFatfpBan = ldblQKwhFatfpBan - ldblQKwhFatfpAUX
                                            End If
                                        End If

                                        If lstrGrupo = "AL" Then
                                            If lintParcialmenteCativo = 1 Then
                                                ldblQKwhFatfpLiv = IIf(IsDBNull(row.Item("kwh_faturado_fora_ponta")), 0, row.Item("kwh_faturado_fora_ponta")) * lintMpr 'Consumo faturado fp
                                                ldblQKwhFatfp = ldblQKwhFatfp - ldblQKwhFatfpLiv
                                                'ldblQKwhFatfpBan = ldblQKwhFatfpBan - ldblQKwhFatfpLiv
                                            Else
                                                ldblQKwhFatfpLiv = IIf(IsDBNull(row.Item("kwh_faturado_fora_ponta")), 0, row.Item("kwh_faturado_fora_ponta")) * lintMpr 'Consumo faturado fp
                                                ldblQKwhFatfp = ldblQKwhFatfp - ldblQKwhFatfpLiv
                                                If ldblQKwhFatfpBan >= 0 Then ldblQKwhFatfpBan = 0
                                            End If
                                        End If

                                    End If

                                    ldblQKwhCons = IIf(IsDBNull(row.Item("valor_total")), 0, row.Item("valor_total")) * lintMpr 'ldblQKwhFatp + ldblQKwhFatfp '+ ldblQKwFatp + ldblQKwFatfp

                                    If lintMicroGeracaoConvenioSefaz = 0 Then

                                        ldblVKwhReversoCompTEQtde = IIf(IsDBNull(row.Item("qtd_COMP. TE")), 0, row.Item("qtd_COMP. TE"))
                                        ldblVKwhReversoCompTUSDQtde = IIf(IsDBNull(row.Item("qtd_COMP. TUSD")), 0, row.Item("qtd_COMP. TUSD"))

                                        ldblVKwhReversoCompTEVlr = IIf(IsDBNull(row.Item("vlr_COMP. TE")), 0, row.Item("vlr_COMP. TE"))
                                        ldblVKwhReversoCompTUSDVlr = IIf(IsDBNull(row.Item("vlr_COMP. TUSD")), 0, row.Item("vlr_COMP. TUSD"))

                                        ldblVKwhReversop = IIf(IsDBNull(row.Item("REVERSO PONTA")), 0, row.Item("REVERSO PONTA")) * lintMpr 'valor Medido Reverso na ponta
                                        ldblVKwhReversop = ldblVKwhReversop + (ldblVKwhReversoCompTEVlr + ldblVKwhReversoCompTUSDVlr)

                                        ldblVKwhReversofp = IIf(IsDBNull(row.Item("REVERSO FORA DE PONTA")), 0, row.Item("REVERSO FORA DE PONTA")) * lintMpr 'valor Medido Reverso fora ponta

                                    Else

                                        ldblVKwhReversoCompTEQtde = IIf(IsDBNull(row.Item("qtd_COMP. TE")), 0, row.Item("qtd_COMP. TE"))
                                        ldblVKwhReversoCompTUSDQtde = IIf(IsDBNull(row.Item("qtd_COMP. TUSD")), 0, row.Item("qtd_COMP. TUSD"))

                                        ldblVKwhReversoCompTEVlr = IIf(IsDBNull(row.Item("vlr_COMP. TE")), 0, row.Item("vlr_COMP. TE"))
                                        ldblVKwhReversoCompTUSDVlr = IIf(IsDBNull(row.Item("vlr_COMP. TUSD")), 0, row.Item("vlr_COMP. TUSD"))

                                        ldblVKwhReversop_sefaz = IIf(IsDBNull(row.Item("REVERSO PONTA")), 0, row.Item("REVERSO PONTA")) * lintMpr 'valor Medido Reverso na ponta
                                        ldblVKwhReversofp_sefaz = IIf(IsDBNull(row.Item("REVERSO FORA DE PONTA")), 0, row.Item("REVERSO FORA DE PONTA")) * lintMpr 'valor Medido Reverso fora ponta

                                    End If

                                    If ldblDiferenca <> 0 Then
                                        ldblVKwhReversop = ldblVKwhReversop + ldblDiferenca '(ldblDiferenca * -1)
                                        ldblDiferencaTot = ldblDiferencaTot + ldblDiferenca
                                    End If

                                    '

                                    ldblQKwContr = IIf(IsDBNull(row.Item("demanda_contratada_ponta")), 0, row.Item("demanda_contratada_ponta"))  'Demanda Contratada p
                                    ldblQKwContr = IIf(IsDBNull(row.Item("demanda_contratada_fora_ponta")), 0, row.Item("demanda_contratada_fora_ponta"))  'Demanda Contratada fp
                                    ldblQKwFatp = IIf(IsDBNull(row.Item("kw_faturado_ponta")), 0, row.Item("kw_faturado_ponta")) * lintMpr  ' + BuscaVlrItem(lstrItens, "0302010022")  'Demanda p
                                    ldblQKwFatfp = IIf(IsDBNull(row.Item("kw_faturado_fora_ponta")), 0, row.Item("kw_faturado_fora_ponta")) * lintMpr ' + BuscaVlrItem(lstrItens, "0302010026") 'Demanda fp

                                    ldblQKwFatUp = IIf(IsDBNull(row.Item("kw_ultrapassagem_ponta")), 0, row.Item("kw_ultrapassagem_ponta")) * lintMpr 'Demanda de ultrapassagem p
                                    ldblQKwFatUfp = IIf(IsDBNull(row.Item("kw_ultrapassado_fora_ponta")), 0, row.Item("kw_ultrapassado_fora_ponta")) * lintMpr 'Demanda de ultrapassagem fp

                                    'Valor
                                    ldblVKwhFatp = 0
                                    ldblVKwhFatfp = 0
                                    ldblVKwhFatpLiv = 0
                                    ldblVKwhFatfpLiv = 0
                                    'ldblTarPSeca = BuscaVlrItem(lstrItens, "01AV011101") 'Tarifa Consumo Lido na Ponta
                                    'ldblTarFPSeca = BuscaVlrItem(lstrItens, "01AV011102") 'Tarifa Consumo Lido na Fora Ponta
                                    'ldblTarPUmida = BuscaVlrItem(lstrItens, "01AV011105") 'Tarifa Consumo Lido na Ponta
                                    'ldblTarFPUmida = BuscaVlrItem(lstrItens, "01AV011106") 'Tarifa Consumo Lido na Fora Ponta
                                    ldblVKwhFatp = IIf(IsDBNull(row.Item("valor_kwh_faturado_ponta")), 0, row.Item("valor_kwh_faturado_ponta")) * lintMpr 'Consumo faturado p
                                    ldblVKwhFatpBan = IIf(IsDBNull(row.Item("bandeira_valor_kwh_fat_ponta")), 0, row.Item("bandeira_valor_kwh_fat_ponta")) * lintMpr 'Consumo faturado p

                                    If lstrGrupo = "AL" Then
                                        If lintParcialmenteCativo = 1 Then
                                            ldblVKwhFatpLiv = IIf(IsDBNull(row.Item("valor_kwh_faturado_ponta")), 0, row.Item("valor_kwh_faturado_ponta")) * lintMpr 'Consumo faturado p
                                        Else
                                            ldblVKwhFatpLiv = IIf(IsDBNull(row.Item("valor_kwh_faturado_ponta")), 0, row.Item("valor_kwh_faturado_ponta")) * lintMpr 'Consumo faturado p
                                            ldblVKwhFatp = ldblVKwhFatp - ldblVKwhFatpLiv
                                            If ldblVKwhFatpBan >= 0 Then ldblVKwhFatpBan = 0
                                        End If
                                    End If

                                    ldblVKwhFatfp = IIf(IsDBNull(row.Item("valor_kwh_faturado_fora_ponta")), 0, row.Item("valor_kwh_faturado_fora_ponta")) * lintMpr 'Consumo faturado fp
                                    ldblVKwhFatfpBan = IIf(IsDBNull(row.Item("bandeira_valor_kwh_fat_fora_ponta")), 0, row.Item("bandeira_valor_kwh_fat_fora_ponta")) * lintMpr 'Consumo faturado fp

                                    If lstrGrupo = "AL" Then
                                        If lintParcialmenteCativo = 1 Then
                                            ldblVKwhFatfpLiv = IIf(IsDBNull(row.Item("valor_kwh_faturado_fora_ponta")), 0, row.Item("valor_kwh_faturado_fora_ponta")) * lintMpr 'Consumo faturado fp
                                        Else
                                            ldblVKwhFatfpLiv = IIf(IsDBNull(row.Item("valor_kwh_faturado_fora_ponta")), 0, row.Item("valor_kwh_faturado_fora_ponta")) * lintMpr 'Consumo faturado fp
                                            ldblVKwhFatfp = ldblVKwhFatfp - ldblVKwhFatfpLiv
                                            If ldblVKwhFatfpBan >= 0 Then ldblVKwhFatfpBan = 0
                                        End If
                                    End If

                                    ldblVKwhDevp = IIf(IsDBNull(row.Item("valor_kwh_devolvido_ponta")), 0, row.Item("valor_kwh_devolvido_ponta")) * lintMpr 'Valor Consumo devolvido na p
                                    ldblVKwhDevfp = IIf(IsDBNull(row.Item("valor_kwh_devolvido_fora_ponta")), 0, row.Item("valor_kwh_devolvido_fora_ponta")) * lintMpr 'Valor Consumo devolvido na fp
                                    ldblVKwhUtrp = IIf(IsDBNull(row.Item("valor_kwh_ultrapassado_ponta")), 0, row.Item("valor_kwh_ultrapassado_ponta")) * lintMpr 'Valor Consumo ultrapassado na p
                                    ldblVKwhUtrfp = IIf(IsDBNull(row.Item("valor_kwh_ultrapassado_fora_ponta")), 0, row.Item("valor_kwh_ultrapassado_fora_ponta")) * lintMpr 'Valor Consumo ultrapassado na fp


                                    ldblVKwhCons = IIf(IsDBNull(row.Item("vlr_kwh_faturado")), 0, row.Item("vlr_kwh_faturado")) * lintMpr
                                    ldblVKwFatp = IIf(IsDBNull(row.Item("valor_kw_faturado_ponta")), 0, row.Item("valor_kw_faturado_ponta")) * lintMpr ' + BuscaVlrItem(lstrItens, "0302020022")  'Demanda p
                                    ldblVKwFatfp = IIf(IsDBNull(row.Item("valor_kw_faturado_fora_ponta")), 0, row.Item("valor_kw_faturado_fora_ponta")) * lintMpr '+ (BuscaVlrItem(lstrItens, "0302020072") * lintMpr) ' + BuscaVlrItem(lstrItens, "0302020026") 'Demanda fp

                                    ''Arlindo dif. demanda
                                    ldblVKwDifFatp = 0 'IIf(IsDBNull(row.Item("valor_kw_faturado_fora_ponta")), 0, row.Item("valor_kw_faturado_fora_ponta")) * lintMpr ' 'Dif. Demanda p
                                    ldblVKwDifFatfp = IIf(IsDBNull(row.Item("valor_dif dem contr")), 0, row.Item("valor_dif dem contr")) * lintMpr 'Dif. Demanda fp
                                    '

                                    If lstrGrupo = "AL" Then
                                        'ldblVKwFatp = ldblVKwFatp + (BuscaVlrItem(lstrItens, "0302060021") * lintMpr) 'dif.Demanda p ***
                                        'ldblVKwFatfp = ldblVKwFatfp + (BuscaVlrItem(lstrItens, "0302060025") * lintMpr) 'dif.Demanda fp ***
                                        ldblVkwDscProv = IIf(IsDBNull(row.Item("valor_desconto_provisorio")), 0, row.Item("valor_desconto_provisorio")) * lintMpr 'Desconto Provisorio
                                        ldblVkwDscReal = IIf(IsDBNull(row.Item("valor_desconto_realizado")), 0, row.Item("valor_desconto_realizado")) * lintMpr 'Desconto real
                                        ldblVkwDevCcee = IIf(IsDBNull(row.Item("valor_devolucao_diferenca_ccee")), 0, row.Item("valor_devolucao_diferenca_ccee")) * lintMpr 'diferença a devolver
                                        ldblVkwCobCcee = IIf(IsDBNull(row.Item("valor_cobranca_diferenca_ccee")), 0, row.Item("valor_cobranca_diferenca_ccee")) * lintMpr 'diferença a cobrar
                                        '
                                        ldblVkwhDscProv = IIf(IsDBNull(row.Item("valor_energia_desconto_provisorio")), 0, row.Item("valor_energia_desconto_provisorio")) * lintMpr 'Desconto Provisorio
                                        ldblVkwhDscReal = IIf(IsDBNull(row.Item("valor_energia_desconto_realizado")), 0, row.Item("valor_energia_desconto_realizado")) * lintMpr 'Desconto real
                                        ldblVkwhDevCcee = IIf(IsDBNull(row.Item("valor_energia_devolucao_diferenca_ccee")), 0, row.Item("valor_energia_devolucao_diferenca_ccee")) * lintMpr 'diferença a devolver
                                        ldblVkwhCobCcee = IIf(IsDBNull(row.Item("valor_energia_cobranca_diferenca_ccee")), 0, row.Item("valor_energia_cobranca_diferenca_ccee")) * lintMpr 'diferença a cobrar
                                    End If

                                    ldblVKwFatUp = IIf(IsDBNull(row.Item("valor_kw_ultrapassagem_ponta")), 0, row.Item("valor_kw_ultrapassagem_ponta")) * lintMpr 'Demanda de ultrapassagem p
                                    ldblVKwFatUfp = IIf(IsDBNull(row.Item("valor_kw_ultrapassado_fora_ponta")), 0, row.Item("valor_kw_ultrapassado_fora_ponta")) * lintMpr 'Demanda de ultrapassagem fp

                                    'Reativo
                                    ldblConsumoReativop = IIf(IsDBNull(row.Item("valor_consumo_reativo_ponta")), 0, row.Item("valor_consumo_reativo_ponta")) * lintMpr 'Consumo Reativo p
                                    ldblConsumoReativofp = IIf(IsDBNull(row.Item("valor_consumo_reativo_fora_ponta")), 0, row.Item("valor_consumo_reativo_fora_ponta")) * lintMpr 'Consumo Reativo fp
                                    ldblDemandaReativap = IIf(IsDBNull(row.Item("valor_demanda_reativo_ponta")), 0, row.Item("valor_demanda_reativo_ponta")) * lintMpr 'Demanda Reativo p
                                    ldblDemandaReativafp = IIf(IsDBNull(row.Item("valor_demanda_reativo_fora_ponta")), 0, row.Item("valor_demanda_reativo_fora_ponta")) * lintMpr 'Demanda Reativo fp

                                End If

                                ldblTip = IIf(IsDBNull(row.Item("valor_cip")), 0, row.Item("valor_cip")) * lintMpr 'Vlr Iluminação Pública.


                                'Tributos
                                ldblIcms1 = IIf(IsDBNull(row.Item("valor_icms")), 0, row.Item("valor_icms")) * lintMpr 'Vlr Icms.
                                ldblIcms2 = IIf(IsDBNull(row.Item("valor_icms")), 0, row.Item("valor_icms")) * lintMpr 'Vlr Icms.
                                ldblPis = IIf(IsDBNull(row.Item("valor_pis")), 0, row.Item("valor_pis")) * lintMpr 'Vlr PIS.
                                ldblCofins = IIf(IsDBNull(row.Item("valor_cofins")), 0, row.Item("valor_cofins")) * lintMpr 'Vlr COFINS.
                                'ldblIcmsSt = IIf(IsDBNull(row.Item("valor_cip")), 0, row.Item("valor_cip")) * lintMpr ***
                                'ldblPisSt = IIf(IsDBNull(row.Item("valor_cip")), 0, row.Item("valor_cip")) * lintMpr ***
                                'ldblCofinsSt = IIf(IsDBNull(row.Item("valor_cip")), 0, row.Item("valor_cip")) * lintMpr ***
                                'ldblIcmsPisCof = IIf(IsDBNull(row.Item("valor_cip")), 0, row.Item("valor_cip")) * lintMpr 'Vlr Icms/Pis/Cofins. ***
                                'ldblSaldoArre = IIf(IsDBNull(row.Item("valor_cip")), 0, row.Item("valor_cip")) * lintMpr ***
                                ldblJuros = IIf(IsDBNull(row.Item("valor_juros_ece")), 0, row.Item("valor_juros_ece")) * lintMpr 'Juros verificar ainda com o calculo.
                                ldblEncargo = IIf(IsDBNull(row.Item("valor_ece")), 0, row.Item("valor_ece")) * lintMpr 'Encargos confirma ainda com o calculo
                                ldblMust = IIf(IsDBNull(row.Item("valor_must")), 0, row.Item("valor_must")) * lintMpr 'EUSD - Must das usinas (EFLUL)

                                ldblTaxados = IIf(IsDBNull(row.Item("valor_taxados")), 0, row.Item("valor_taxados")) * lintMpr
                                ldblDiversos = IIf(IsDBNull(row.Item("valor_diversos")), 0, row.Item("valor_diversos")) * lintMpr
                                ldblEncFinan = IIf(IsDBNull(row.Item("valor_encargos_financeiros")), 0, row.Item("valor_encargos_financeiros")) * lintMpr
                                ldblConvenios = IIf(IsDBNull(row.Item("valor_convenios")), 0, row.Item("valor_convenios")) * lintMpr
                                ldblRetencao = IIf(IsDBNull(row.Item("valor_retencao")), 0, row.Item("valor_retencao")) * lintMpr
                                ldblDevolucao = IIf(IsDBNull(row.Item("valor_devolucao")), 0, row.Item("valor_devolucao")) * lintMpr

                                'Isento icms

                                ldblIsentoIcms = 0

                                If ldblIcms1 = 0 Then
                                    ldblIsentoIcms = ldblBaseIcms1
                                End If
                                If ldblIcms2 = 0 Then
                                    ldblIsentoIcms = ldblIsentoIcms + ldblBaseIcms2
                                End If
                                If lstrGrupo = "AL" Then
                                    'ldblIsentoIcms = BuscaVlrItem(lstrItens, "0302030030") * lintMpr
                                    'ldblDiferido = BuscaVlrItem(lstrItens, "0302030030") * lintMpr
                                End If


                                'Busca valor de Taxas, Diversos e Convenios
                                For IndCodServ = 1 To Len(Trim(lstrItens))

                                    BuscaCodItem(IndCodServ, lstrItens)
                                    If IsNumeric(VlrCodServ) Then
                                        ldblAux = Val(VlrCodServ)
                                    Else
                                        ldblAux = 0
                                    End If

                                    If ldblAux < 0 Then
                                        ldblAux = ldblAux * -1
                                    End If

                                    lblnInclui = False

                                    'taxados
                                    If Mid(CodServ, 1, 4) = "9040" Or Mid(CodServ, 1, 4) = "9050" Then
                                        'ldblTaxados = ldblTaxados + (ldblAux * lintMpr)
                                        lblnInclui = True
                                    End If

                                    'diversos
                                    If Mid(CodServ, 1, 4) = "9080" And Not (Mid(CodServ, 1, 10) = "9080000061" Or Mid(CodServ, 1, 10) = "9080000066" Or Mid(CodServ, 1, 10) = "9080000067") Then
                                        'ldblDiversos = ldblDiversos + (ldblAux * lintMpr)
                                        lblnInclui = True
                                    End If

                                    'diversos
                                    If Mid(CodServ, 1, 10) = "9080000061" Or Mid(CodServ, 1, 10) = "9080000066" Or Mid(CodServ, 1, 10) = "9080000067" Then
                                        'ldblEncFinan = ldblEncFinan + (ldblAux * lintMpr)
                                        lblnInclui = True
                                    End If

                                    'convenios
                                    If Mid(CodServ, 1, 4) = "9030" Then
                                        'ldblConvenios = ldblConvenios + (ldblAux * lintMpr)
                                        lblnInclui = True
                                    End If

                                    'EUSD - must
                                    If Mid(CodServ, 1, 10) = "0302020032" Then
                                        lblnInclui = True
                                    End If

                                    'retencoes
                                    If Mid(CodServ, 1, 10) = "9070000088" Then 'Não será mais usado (futuro)
                                        'ldblRetencao = ldblRetencao + (ldblAux * lintMpr)
                                        lblnInclui = True
                                    End If

                                    If Mid(CodServ, 1, 4) = "9090" Then
                                        'ldblRetencao = ldblRetencao + (ldblAux * lintMpr)
                                        lblnInclui = True
                                    End If

                                    'Devoluções
                                    If Mid(CodServ, 1, 4) = "9070" And Mid(CodServ, 1, 10) <> "9070000088" And Mid(CodServ, 1, 10) <> "9070000008" And Mid(CodServ, 1, 10) <> "9070000009" And Mid(CodServ, 1, 10) <> "9070000002" And Mid(CodServ, 1, 10) <> "9070000094" And Mid(CodServ, 1, 10) <> "9070000095" And Mid(CodServ, 1, 10) <> "9070000001" And Mid(CodServ, 1, 10) <> "9070000003" And Mid(CodServ, 1, 10) <> "9070000062" Then
                                        'ldblDevolucao = ldblDevolucao + (ldblAux * lintMpr)
                                        lblnInclui = True
                                    End If

                                    'Arlindo 20/05/21
                                    If Mid(CodServ, 1, 10) = "9070000008" Or Mid(CodServ, 1, 10) = "9070000009" Or Mid(CodServ, 1, 10) = "9070000002" Or Mid(CodServ, 1, 10) = "9070000094" Or Mid(CodServ, 1, 10) = "9070000095" Or Mid(CodServ, 1, 10) = "9070000001" Or Mid(CodServ, 1, 10) = "9070000003" Or Mid(CodServ, 1, 10) = "9070000062" Then
                                        'ldblDevolucao_1 = ldblDevolucao_1 + (ldblAux * lintMpr)
                                        lblnInclui = True
                                    End If

                                    If lblnInclui = True Then

                                        lstrSqlIAx = lstrSqlIAx & "('" & CodServ & "','" & codTodescri(CodServ) & "'" & "," & Replace(CStr(ldblAux * lintMpr), ",", ".") & ",'" & lstrZona & "'" & ",'" & Microsoft.VisualBasic.Left(lstrGrupo, 1) & "'), "

                                        lintContInsertItens = lintContInsertItens + 1

                                        If lintContInsertItens > 300 Then
                                            lstrSqlIte = lstrSqlIte & Microsoft.VisualBasic.Left(lstrSqlIAx, Len(lstrSqlIAx) - 2)
                                            objTempEstatisItens.TABLE = lstrSqlIte
                                            repositorioTempEstatisItens.Execute_2(objTempEstatisItens)

                                            lstrSqlIte = ""

                                            If CriaTabelas(lstrSqlPri, lstrSqlIte, False, False, True) Then
                                                lstrSqlIAx = ""
                                                lintContInsertItens = 1
                                            End If


                                        End If

                                    End If

                                Next IndCodServ

                                lstrSqlPAx = lstrSqlPAx & "('" & lstrClasse & "', " 'classe

                                'Convencional
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhCons), ",", ".") & "', " 'qkwh_cons
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFat), ",", ".") & "', " 'qkwh_fat
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatBan), ",", ".") & "', " 'qkwh_fat_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwContr), ",", ".") & "', " 'qkw_contr
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwFat), ",", ".") & "', " 'qkw_fat
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhCons), ",", ".") & "', " 'vkwh_cons

                                If (ldblVkWhFatTU + ldblVkWhFatTE) > 0 Then
                                    lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkWhFatTU + ldblVkWhFatTE), ",", ".") & "', " 'vkwh_fat
                                    lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkWhFatTEBan), ",", ".") & "', " 'vkwh_fat_ban
                                Else
                                    lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFat), ",", ".") & "', " 'vkwh_fat
                                    lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatBan), ",", ".") & "', " 'vkwh_fat_ban
                                End If

                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwFat), ",", ".") & "', " 'vkw_fat
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblConsumoReativo), ",", ".") & "', " 'vconreat
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblDemandaReativa), ",", ".") & "', " 'vdemreat

                                'Horosazonal
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatp), ",", ".") & "', " 'qkwh_fat_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFati), ",", ".") & "', " 'qkwh_fat_i
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatfp), ",", ".") & "', " 'qkwh_fat_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatpBan), ",", ".") & "', " 'qkwh_fat_p_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatiBan), ",", ".") & "', " 'qkwh_fat_i_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatfpBan), ",", ".") & "', " 'qkwh_fat_fp_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatpLiv), ",", ".") & "', " 'qkwh_fat_p_liv
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhFatfpLiv), ",", ".") & "', " 'qkwh_fat_fp_liv
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhDevp), ",", ".") & "', " 'qkwh_dev_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhDevfp), ",", ".") & "', " 'qkwh_dev_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhUtrp), ",", ".") & "', " 'qkwh_utr_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhUtrfp), ",", ".") & "', " 'qkwh_utr_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwContrp), ",", ".") & "', " 'qkw_contr_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwContrfp), ",", ".") & "', " 'qkw_contr_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwFatp), ",", ".") & "', " 'qkw_fat_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwFatfp), ",", ".") & "', " 'qkw_fat_fp

                                ' Arlindo dif. demanda
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwDifFatp), ",", ".") & "', " 'qkw_dif_fat_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwDifFatfp), ",", ".") & "', " 'qkw_dif_fat_fp
                                '

                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwFatUp), ",", ".") & "', " 'qkw_fatu_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwFatUfp), ",", ".") & "', " 'qkw_fatu_fp

                                'valor
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatp), ",", ".") & "', " 'vkwh_fat_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFati), ",", ".") & "', " 'vkwh_fat_i
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatfp), ",", ".") & "', " 'vkwh_fat_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatpBan), ",", ".") & "', " 'vkwh_fat_p_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatiBan), ",", ".") & "', " 'vkwh_fat_i_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatfpBan), ",", ".") & "', " 'vkwh_fat_fp_ban
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatpLiv), ",", ".") & "', " 'vkwh_fat_p_liv
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhFatfpLiv), ",", ".") & "', " 'vkwh_fat_fp_liv
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhDevp), ",", ".") & "', " 'vkwh_dev_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhDevfp), ",", ".") & "', " 'vkwh_dev_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhUtrp), ",", ".") & "', " 'vkwh_utr_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhUtrfp), ",", ".") & "', " 'vkwh_utr_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwFatp), ",", ".") & "', " 'vkw_fat_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwFatfp), ",", ".") & "', " 'vkw_fat_fp

                                ' Arlindo dif. demanda
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwDifFatp), ",", ".") & "', " 'vkw_dif_fat_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwDifFatfp), ",", ".") & "', " 'vkw_dif_fat_fp
                                '

                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwFatUp), ",", ".") & "', " 'vkw_fatu_p
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwFatUfp), ",", ".") & "', " 'vkw_fatu_fp
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwDscProv), ",", ".") & "', " 'vkw_dsc_prov
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwDscReal), ",", ".") & "', " 'vkw_dsc_real
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwDevCcee), ",", ".") & "', " 'vkw_dev_ccee
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwCobCcee), ",", ".") & "', " 'vkw_cob_ccee

                                '
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwhDscProv), ",", ".") & "', " 'vkwh_dsc_prov
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwhDscReal), ",", ".") & "', " 'vkwh_dsc_real
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwhDevCcee), ",", ".") & "', " 'vkwh_dev_ccee
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVkwhCobCcee), ",", ".") & "', " 'vkwh_cob_ccee
                                '

                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblConsumoReativop), ",", ".") & "', " 'vconreat_p = Consumo Reativo ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblConsumoReativofp), ",", ".") & "', " 'vconreat_fp = Consumo Reativo fora ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblDemandaReativap), ",", ".") & "', " 'vdemreat_p = Demanda Reativo ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblDemandaReativafp), ",", ".") & "', " 'vdemreat_fp = Demanda Reativo fora ponta
                                'lstrSqlPAx = lstrSqlPAx & "'" & Replace(ldblQKwhReverso, ",", ".") & "', " 'reverso
                                'lstrSqlPAx = lstrSqlPAx & "'" & Replace(ldblVKwhReverso, ",", ".") & "', " 'valor
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhReversop), ",", ".") & "', " 'Qtd Medido reverso ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhReversoi), ",", ".") & "', " 'Qtd Medido reverso intermediario
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhReversofp), ",", ".") & "', " 'Qtd Medido reverso fora ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhReversop), ",", ".") & "', " 'valor Medido reverso ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhReversoi), ",", ".") & "', " 'valor Medido reverso intermediario
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhReversofp), ",", ".") & "', " 'valor Medido reverso fora ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhReversop_sefaz), ",", ".") & "', " 'Qtd Medido reverso ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhReversoi_sefaz), ",", ".") & "', " 'Qtd Medido reverso intermediario
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblQKwhReversofp_sefaz), ",", ".") & "', " 'Qtd Medido reverso fora ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhReversop_sefaz), ",", ".") & "', " 'valor Medido reverso ponta
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhReversoi_sefaz), ",", ".") & "', " 'valor Medido reverso intermediario
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblVKwhReversofp_sefaz), ",", ".") & "', " 'valor Medido reverso fora ponta

                                'Outros
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblTip), ",", ".") & "', " 'tip
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblSaldoArre), ",", ".") & "', " 'arrendodamento
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblEncFinan), ",", ".") & "', " 'encargos financeiros
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblIcms1 + ldblIcms2), ",", ".") & "', " 'icms
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblPis), ",", ".") & "', " 'pis
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblCofins), ",", ".") & "', " 'cofins
                                '
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblIcmsSt), ",", ".") & "', " 'icms - st
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblPisSt), ",", ".") & "', " 'pis - st
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblCofinsSt), ",", ".") & "', " 'cofins - st
                                '
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblBaseIcms1 + ldblBaseIcms2), ",", ".") & "', " 'base icms
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblBasePis), ",", ".") & "', " 'base pis
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblBaseCofins), ",", ".") & "', " 'base cofins
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblIcmsPisCof), ",", ".") & "', " 'icms/pis/cofins
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblIsentoIcms), ",", ".") & "', " 'Isento icms
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblDiferido), ",", ".") & "', " 'diferido
                                '
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblDifEltrbr), ",", ".") & "', " 'dif_eltrbr
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblJuros), ",", ".") & "', " 'juros
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblEncargo), ",", ".") & "', " 'encargo
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(CStr(ldblMust), ",", ".") & "', " 'must
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblValorTot)), ",", ".") & "', " 'total
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblTaxados)), ",", ".") & "', " 'taxados
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblDiversos)), ",", ".") & "', " 'diversos
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblConvenios)), ",", ".") & "', " 'convenios
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblDevolucao)), ",", ".") & "', " 'descontos
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblDevolucao_1)), ",", ".") & "', " 'descontos_1
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblRetencao)), ",", ".") & "', " 'retencao
                                '
                                lstrSqlPAx = lstrSqlPAx & "'" & lstrFlgMedFat & "', " 'flgmedtfat = Fatura que foi cancelada e reprocessada
                                lstrSqlPAx = lstrSqlPAx & "'" & lintFaturaFinal & "', " 'fatura_final
                                lstrSqlPAx = lstrSqlPAx & "'" & lintIrrigacaoAquicultura & "', " 'irrigacao_aquicultura

                                lstrSqlPAx = lstrSqlPAx & "'" & lintMicroGeracao & "', " 'micro geracao
                                lstrSqlPAx = lstrSqlPAx & "'" & lintMicroGeracaoDistribuida & "', " 'micro geracao
                                lstrSqlPAx = lstrSqlPAx & "'" & lintMicroGeracaoConvenioSefaz & "', " 'micro geracao convenio Sefaz
                                lstrSqlPAx = lstrSqlPAx & "'" & lintTarifaBranca & "', " 'tarifa_branca

                                '************************************

                                If lintMicroGeracaoConvenioSefaz = 0 Then
                                    'lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblVKwhReverso + ldblVKwhReversop + ldblVKwhReversofp)), ",", ".") & "', " 'reverso para o importe
                                    lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ldblVKwhReversop + ldblVKwhReversoi + ldblVKwhReversofp)), ",", ".") & "', " 'reverso para o importe
                                Else
                                    lstrSqlPAx = lstrSqlPAx & "'0',"
                                End If

                                lstrSqlPAx = lstrSqlPAx & "'" & lstrFlgSt & "', " 'situação
                                '
                                lstrSqlPAx = lstrSqlPAx & "'" & lstrFase & "', " 'fase

                                lstrGrupo = IIf(Microsoft.VisualBasic.Left(lstrGrupo, 1) = "A", lstrGrupo, Microsoft.VisualBasic.Left(lstrGrupo, 1))

                                If lstrGrupo = "AL" Then
                                    lstrGrupo = lstrGrupo & IIf(lintParcialmenteCativo = 1, "P", "")
                                    lstrGrupo = lstrGrupo & IIf(lintLivreVerde = 1, "V", "A")
                                End If

                                lstrSqlPAx = lstrSqlPAx & "'" & lstrGrupo & "',"
                                lstrSqlPAx = lstrSqlPAx & "'" & lstrZona & "','" & lstrLivro & "','" & lstrConta & "','" & Replace(lstrNome, "'", "\'") & "',"

                                If lstrGrupoT = "AL" Then
                                    lstrGrupoT = lstrGrupoT & IIf(lintParcialmenteCativo = 1, "P", "")
                                    lstrGrupoT = lstrGrupoT & IIf(lintLivreVerde = 1, "V", "A")
                                End If

                                lstrSqlPAx = lstrSqlPAx & "'" & lstrGrupoT & "',"

                                If lstrGrupoT = "ALA" Then
                                    lintSequencia = 1
                                ElseIf lstrGrupoT = "ALPA" Then
                                    lintSequencia = 2
                                ElseIf lstrGrupoT = "ALV" Then
                                    lintSequencia = 3
                                ElseIf lstrGrupoT = "ALPV" Then
                                    lintSequencia = 4
                                Else
                                    lintSequencia = 0
                                End If

                                lstrSqlPAx = lstrSqlPAx & "'" & lintSequencia & "',"
                                'lstrSqlPAx = lstrSqlPAx & "'" & lstrMesAno & "'"
                                'lstrSqlPAx = lstrSqlPAx & "), "

                                lstrSqlPAx = lstrSqlPAx & "'" & lstrMesAno & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & llngMatricula & "',"
                                lstrSqlPAx = lstrSqlPAx & "'" & dNumNf & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & sGrupo_tarifario & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & sClasse_faturada & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & sDescricao_classe & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & sMesano_referencia & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & sAnomes_fat & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(ldteEmissao, "yyyy-MM-dd") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(ldteApresentacao, "yyyy-MM-dd") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(dData_vencimento, "yyyy-MM-dd") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(dData_leitura_atual, "yyyy-MM-dd") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(dData_leitura_anterior, "yyyy-MM-dd") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_juros_ece)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_diferenca_ece)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_ece)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_liquido)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dqtde_fx1)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dqtde_fx2)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dqtde_fx3)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dqtde_fx4)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvlr_fx1)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvlr_fx2)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvlr_fx3)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvlr_fx4)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dkwh_lido)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dbase_icms_1)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(daliquota_icms_1)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_icms_1)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dbase_icms_2)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(daliquota_icms_2)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_icms_2)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dAliquota_PIS)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dAliquota_COFINS)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dreceitas_financeiras)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dressarcimento_idqual)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_encargo_uso_sis_trans)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(ddesconto_must)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dencargo_kwh_faturado_ponta)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dencargo_valor_kwh_faturado_ponta)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dencargo_kwh_faturado_fora_ponta)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dencargo_valor_kwh_faturado_fora_ponta)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dmwh_medio)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dmwh_medio_horas)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dVALOR_REVERSO)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dVALOR_REVERSO_BAN)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_PONTA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_PONTA_BANDEIRA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_FORA_DE_PONTA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_FORA_DE_PONTA_BANDEIRA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dbandeira_vlr_kwh_fat)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dbandeira_valor_kwh_fat_ponta)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dbandeira_valor_kwh_fat_fora_ponta)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_energia_desconto_provisorio)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_energia_desconto_realizado)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_energia_devolucao_diferenca_ccee)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dvalor_energia_cobranca_diferenca_ccee)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dCONSUMO_PONTA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dCONSUMO_FORA_PONTA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_FORA_PONTA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_RESIDUO_FORA_PONTA)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dTUSD)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dCONSUMO_MEDIDO)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Replace(Trim(Str(dREVERSO_LIDO)), ",", ".") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(ddatast, "yyyy-MM-dd") & "', "
                                lstrSqlPAx = lstrSqlPAx & "'" & Format(ddata_pagamento, "yyyy-MM-dd") & "' "
                                lstrSqlPAx = lstrSqlPAx & "), "

                                lintContInsertPri = lintContInsertPri + 1

                                'If bPlan = True Then
                                '    sGeraPlan_(sGrupo_tarifario, lstrGrupo, lstrClasse, sClasse_faturada, sDescricao_classe, lstrZona, lstrLivro,
                                '               lstrConta, llngMatricula, lstrNome, dNumNf, lstrMesAno, sMesano_referencia, sAnomes_fat, dData_emissao,
                                '               dData_apresentacao, dData_vencimento, dData_leitura_atual, dData_leitura_anterior,
                                '               ldblConsumoReativo, ldblDemandaReativa, ldblConsumoReativop, ldblConsumoReativofp,
                                '               ldblDemandaReativap, ldblDemandaReativafp, ldblQKwFat, ldblVKwFat, ldblQKwFatp,
                                '               ldblVKwFatp, ldblQKwFatfp, ldblVKwFatfp, ldblQKwhDevp, ldblVKwhDevp,
                                '               ldblQKwhDevfp, ldblVKwhDevfp, ldblQKwhUtrp, ldblVKwhUtrp, ldblQKwhUtrfp, ldblVKwhUtrfp, ldblQKwFat, ldblVKwFat,
                                '               ldblQKwFatp, ldblVKwFatp, ldblQKwFatfp, ldblVKwFatfp, ldblQKwFatUp, ldblVKwFatUp,
                                '               ldblQKwFatUp, ldblVKwFatUp, ldblQKwFatUp, ldblVKwFatUp, ldblVkwDscProv, ldblVkwDscReal,
                                '               ldblVkwhDevCcee, ldblVkwhCobCcee, ldblConvenios, ldblDiversos, ldblTaxados, ldblDevolucao,
                                '               0, ldblRetencao, ldblTip, ldblJuros, dvalor_diferenca_ece, dvalor_ece, ldblMust, ldblIcms1, ldblPis, ldblCofins,
                                '               ldblValorTot, dvalor_liquido, ldblQKwContr, ldblQKwContrp, ldblQKwContrfp, dqtde_fx1, dqtde_fx2, dqtde_fx3,
                                '               dqtde_fx4, dvlr_fx1, dvlr_fx2, dvlr_fx3, dvlr_fx4, dkwh_lido, lstrFase,
                                '               dbase_icms_1, daliquota_icms_1, dvalor_icms_1, dbase_icms_2, daliquota_icms_2,
                                '               dvalor_icms_2, ldblBasePis, dAliquota_PIS, ldblBaseCofins, dAliquota_COFINS, dreceitas_financeiras,
                                '               dressarcimento_idqual, dvalor_encargo_uso_sis_trans, ddesconto_must,
                                '               dencargo_kwh_faturado_ponta, dencargo_valor_kwh_faturado_ponta, dencargo_kwh_faturado_fora_ponta,
                                '               dencargo_valor_kwh_faturado_fora_ponta, dmwh_medio, dmwh_medio_horas, 0,
                                '               dVALOR_REVERSO, dVALOR_REVERSO_BAN, dREVERSO_PONTA, dREVERSO_PONTA_BANDEIRA,
                                '               dREVERSO_FORA_PONTA, dREVERSO_FORA_DE_PONTA_BANDEIRA, dbandeira_vlr_kwh_fat,
                                '               dbandeira_valor_kwh_fat_ponta, dbandeira_valor_kwh_fat_fora_ponta,
                                '               dvalor_energia_desconto_provisorio, dvalor_energia_desconto_realizado, dvalor_energia_devolucao_diferenca_ccee,
                                '               dvalor_energia_cobranca_diferenca_ccee, dCONSUMO_PONTA, dCONSUMO_FORA_PONTA, dREVERSO_FORA_PONTA,
                                '               dREVERSO_RESIDUO_FORA_PONTA, dTUSD, dCONSUMO_MEDIDO, dREVERSO_LIDO,
                                '               lstrFlgSt, ddatast, ddata_pagamento, 0)

                                'Else
                                If lintContInsertPri > 300 Then
                                        lstrSqlPri = lstrSqlPri & Microsoft.VisualBasic.Left(lstrSqlPAx, Len(lstrSqlPAx) - 2)
                                        objTempEstatis.TABLE = lstrSqlPri
                                        repositorioTempEstatis.Execute_2(objTempEstatis)

                                        lstrSqlPri = ""

                                        If CriaTabelas(lstrSqlPri, lstrSqlIte, True, True, False) Then
                                            lstrSqlPAx = ""
                                            lintContInsertPri = 1
                                        End If

                                    End If
                                End If
                            'End If

                            BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 1)
                            System.Windows.Forms.Application.DoEvents()

                        Next

                        If bPlan = True Then

                            ExcelPlanilha.SaveAs(txtArq.Text)
                            ExcelPasta.Close()
                            ExcelAPP.Quit()

                            MessageBox.Show("Planilha gerada com sucesso !", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information)

                        Else
                            If lintContInsertItens > 0 And Len(Trim(lstrSqlIAx)) > 0 Then
                                lstrSqlIte = lstrSqlIte & Microsoft.VisualBasic.Left(lstrSqlIAx, Len(lstrSqlIAx) - 2)
                                objTempEstatisItens.TABLE = lstrSqlIte
                                repositorioTempEstatisItens.Execute_2(objTempEstatisItens)
                                lstrSqlIte = ""
                            End If

                            If lintContInsertPri > 0 And Len(Trim(lstrSqlPAx)) > 0 Then
                                lstrSqlPri = lstrSqlPri & Microsoft.VisualBasic.Left(lstrSqlPAx, Len(lstrSqlPAx) - 2)
                                objTempEstatis.TABLE = lstrSqlPri
                                repositorioTempEstatis.Execute_2(objTempEstatis)
                                lstrSqlPri = ""
                            End If
                        End If
                        lblnRetorno = True


                    End If 'Criatabelas

                Else
                    MessageBox.Show("Não existem faturas no período selecionado!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information)
                lblnRetorno = False
            End If

            End If

            MontaTabela = lblnRetorno

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: MontaTabela" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Function
        End Try

    End Function

    Private Function MontaFiltroDataLeitura(ByVal astrTabela As String) As String

        Dim lstrRetorno As String
        Dim lstrAuxiliar As String
        Dim llngConta As Integer


        Try

            'Filtra Por data de Vencimento

            lstrAuxiliar = ""
            lstrRetorno = ""

            With Me.lsvDtLeit.Items

                If .Count > 0 Then

                    'If .Item(1).Checked = False Then
                    'If .Item(1).Checked = True Then

                    For llngConta = 0 To .Count - 1

                            If .Item(llngConta).Checked Then
                                lstrAuxiliar = lstrAuxiliar & """" & VB6.Format(CDate(.Item(llngConta).Text), "yyyy-MM-dd") & """, "
                            End If

                        Next llngConta

                        If Len(Trim(lstrAuxiliar)) > 0 Then
                            lstrAuxiliar = Microsoft.VisualBasic.Left(lstrAuxiliar, Len(lstrAuxiliar) - 2)
                            lstrRetorno = "    AND " & astrTabela & ".DATALEIT IN(" & lstrAuxiliar & ") "
                        End If

                    'End If

                End If

            End With

            MontaFiltroDataLeitura = lstrRetorno

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: MontaFiltroDataLeitura" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Function
        End Try

    End Function

    Private Function BuscaNome(ByVal alngConsId As Integer, ByVal alngUnidId As Integer, ByVal astrGrupo As String) As String

        Dim lstrRet As String

        Dim vlist

        Dim objUCFaturamento As New entidadeUCFaturamento
        Dim repositorioUCFaturamento As New repositorioUCFaturamento

        Dim objConsum As New entidadeConsum
        Dim repositorioConsum As New repositorioConsum


        Try

            lstrRet = ""

            objUCFaturamento.GRUPO = LCase(astrGrupo)
            objUCFaturamento.UNID_ID = alngUnidId
            objUCFaturamento.CONS_ID = alngConsId

            vlist = repositorioUCFaturamento.Select_13(objUCFaturamento)

            If vlist.Count > 0 Then
                For Each objUCFaturamentoFor As entidadeUCFaturamento In vlist
                    lstrRet = Trim(IIf(IsDBNull(objUCFaturamentoFor.NOME), "", objUCFaturamentoFor.NOME))
                Next
            End If



            If lstrRet = "" Then

                objConsum.CONSREG = alngConsId

                vlist = repositorioConsum.Select(objConsum)

                If vlist.Count > 0 Then
                    For Each objConsumFor As entidadeConsum In vlist
                        lstrRet = Trim(IIf(IsDBNull(objConsumFor.NOME), "", objConsumFor.NOME))
                    Next
                End If


            End If


            If lstrRet = "" Then lstrRet = "NOME INDEFINIDO"

            BuscaNome = lstrRet


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: BuscaNome" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Function
        End Try

    End Function

    Private Sub RelEstat_Operacional(ByVal astrGrupo As String, Optional ByVal astrZona As String = "", Optional ByVal astrCabecTitulo As String = "", Optional ByVal astrCabecGrupo As String = "")

        Dim lstrSqlP As String
        Dim lstrSql As String
        Dim lstrSql0 As String
        Dim lstrSql1 As String
        Dim lstrSql1V As String
        Dim lstrSql1A As String
        Dim lstrSqlFimAno As String
        Dim lstrSql2 As String
        Dim lstrSql3 As String
        Dim strTexto As String
        Dim lngIni As Integer
        Dim lngFim As Integer
        Dim intLinha As Short
        Dim lintClas As Short
        Dim lintAux As Short
        Dim lintAuxVerde As Short
        Dim lintAuxAzul As Short
        Dim lblnCanBX As Boolean 'se teve cancelada na classe baixa renda
        Dim lblnCanRE As Boolean 'se teve cancelada na classe residencial
        Dim lblnCanGE As Boolean 'se teve cancelada na classe geral
        Dim lblnCanIN As Boolean 'se teve cancelada na classe industrial
        Dim lblnCanLV As Boolean 'se teve cancelada na classe livre
        Dim lblnCanCO As Boolean 'se teve cancelada na classe comercial
        Dim lblnCanRU As Boolean 'se teve cancelada na classe rural
        Dim lblnCanPP As Boolean 'se teve cancelada na poder publico
        Dim lblnCanIP As Boolean 'se teve cancelada na iluminacao publica
        Dim lblnCanSP As Boolean 'se teve cancelada na serviço publico
        Dim lblnCanCP As Boolean 'se teve cancelada na consumo proprio
        Dim lstrAux As String
        Dim lintGrupoVerde As Short
        Dim lintGrupoAzul As Short
        Dim sTextoTotalAssociados As String

        Dim dt As DataTable
        Dim dt_1 As DataTable

        Dim objTempEstatis As New entidadeTempEstatis
        Dim repositorioTempEstatis As New repositorioTempEstatis

        Try

            lstrAux = Me.lblInfo.Text

            lintGrupoVerde = 0
            lintGrupoAzul = 0
            llngNconsFimAno = 0
            lblnCanBX = False
            lblnCanRE = False
            lblnCanGE = False
            lblnCanIN = False
            lblnCanLV = False
            lblnCanCO = False
            lblnCanRU = False
            lblnCanPP = False
            lblnCanIP = False
            lblnCanSP = False
            lblnCanCP = False

            istrGrupoG = astrGrupo

            lstrSql = ""

            'Convencional
            'Consumo
            lstrSql = lstrSql & "       SUM(qkwh_cons) qkwh_cons, "
            lstrSql = lstrSql & "       SUM(vkwh_cons) vkwh_cons, "
            lstrSql = lstrSql & "       SUM(qkwh_fat) qkwh_fat, "
            lstrSql = lstrSql & "       SUM(vkwh_fat) vkwh_fat, "
            lstrSql = lstrSql & "       SUM(qkwh_fat_ban) qkwh_fat_ban, "
            lstrSql = lstrSql & "       SUM(vkwh_fat_ban) vkwh_fat_ban, "

            'Demanda
            lstrSql = lstrSql & "       SUM(qkw_fat) qkw_fat, "
            lstrSql = lstrSql & "       SUM(vkw_fat) vkw_fat, "

            'Reativo
            lstrSql = lstrSql & "       SUM(vconreat) vconreat, "
            lstrSql = lstrSql & "       SUM(vdemreat) vdemreat, "

            'Horosazonal
            'Consumo
            lstrSql = lstrSql & "       SUM(qkwh_fat_p) qkwh_fat_p, "
            lstrSql = lstrSql & "       SUM(vkwh_fat_p) vkwh_fat_p, "
            lstrSql = lstrSql & "       SUM(qkwh_fat_i) qkwh_fat_i, "
            lstrSql = lstrSql & "       SUM(vkwh_fat_i) vkwh_fat_i, "
            lstrSql = lstrSql & "       SUM(qkwh_fat_fp) qkwh_fat_fp, "
            lstrSql = lstrSql & "       SUM(vkwh_fat_fp) vkwh_fat_fp, "
            lstrSql = lstrSql & "       SUM(qkwh_fat_p_ban) qkwh_fat_p_ban, "
            lstrSql = lstrSql & "       SUM(vkwh_fat_p_ban) vkwh_fat_p_ban, "
            lstrSql = lstrSql & "       SUM(qkwh_fat_i_ban) qkwh_fat_i_ban, "
            lstrSql = lstrSql & "       SUM(vkwh_fat_i_ban) vkwh_fat_i_ban, "
            lstrSql = lstrSql & "       SUM(qkwh_fat_fp_ban) qkwh_fat_fp_ban, "
            lstrSql = lstrSql & "       SUM(vkwh_fat_fp_ban) vkwh_fat_fp_ban, "
            lstrSql = lstrSql & "       SUM(qkwh_fat_p_liv) qkwh_fat_p_liv, "
            lstrSql = lstrSql & "       SUM(vkwh_fat_p_liv) vkwh_fat_p_liv, "
            lstrSql = lstrSql & "       SUM(qkwh_fat_fp_liv) qkwh_fat_fp_liv, "
            lstrSql = lstrSql & "       SUM(vkwh_fat_fp_liv) vkwh_fat_fp_liv, "
            lstrSql = lstrSql & "       SUM(qkwh_dev_p) qkwh_dev_p, "
            lstrSql = lstrSql & "       SUM(vkwh_dev_p) vkwh_dev_p, "
            lstrSql = lstrSql & "       SUM(qkwh_dev_fp) qkwh_dev_fp, "
            lstrSql = lstrSql & "       SUM(vkwh_dev_fp) vkwh_dev_fp, "
            lstrSql = lstrSql & "       SUM(qkwh_utr_p) qkwh_utr_p, "
            lstrSql = lstrSql & "       SUM(vkwh_utr_p) vkwh_utr_p, "
            lstrSql = lstrSql & "       SUM(qkwh_utr_fp) qkwh_utr_fp, "
            lstrSql = lstrSql & "       SUM(vkwh_utr_fp) vkwh_utr_fp, "

            'Demanda
            lstrSql = lstrSql & "       SUM(qkw_fat_p) qkw_fat_p, "
            lstrSql = lstrSql & "       SUM(vkw_fat_p) vkw_fat_p, "
            lstrSql = lstrSql & "       SUM(qkw_fat_fp) qkw_fat_fp, "
            lstrSql = lstrSql & "       SUM(vkw_fat_fp) vkw_fat_fp, "

            ' Arlindo dif. demanda
            lstrSql = lstrSql & "     SUM(qkw_dif_fat_p) qkw_dif_fat_p, "
            lstrSql = lstrSql & "     SUM(vkw_dif_fat_p) vkw_dif_fat_p, "
            lstrSql = lstrSql & "     SUM(qkw_dif_fat_fp) qkw_dif_fat_fp, "
            lstrSql = lstrSql & "     SUM(vkw_dif_fat_fp) vkw_dif_fat_fp, "

            '
            lstrSql = lstrSql & "       SUM(qkw_fatu_p) qkw_fatu_p, "
            lstrSql = lstrSql & "       SUM(vkw_fatu_p) vkw_fatu_p, "
            lstrSql = lstrSql & "       SUM(qkw_fatu_fp) qkw_fatu_fp, "
            lstrSql = lstrSql & "       SUM(vkw_fatu_fp) vkw_fatu_fp, "

            'Livres - CCEE
            lstrSql = lstrSql & "       SUM(vkw_dsc_prov) vkw_dsc_prov, "
            lstrSql = lstrSql & "       SUM(vkw_dsc_real) vkw_dsc_real, "
            lstrSql = lstrSql & "       SUM(vkw_dev_ccee) vkw_dev_ccee, "
            lstrSql = lstrSql & "       SUM(vkw_cob_ccee) vkw_cob_ccee, "

            '
            lstrSql = lstrSql & "       SUM(vkwh_dsc_prov) vkwh_dsc_prov, "
            lstrSql = lstrSql & "       SUM(vkwh_dsc_real) vkwh_dsc_real, "
            lstrSql = lstrSql & "       SUM(vkwh_dev_ccee) vkwh_dev_ccee, "
            lstrSql = lstrSql & "       SUM(vkwh_cob_ccee) vkwh_cob_ccee, "

            'Reativos
            lstrSql = lstrSql & "       SUM(vconreat_p) vconreat_p, "
            lstrSql = lstrSql & "       SUM(vconreat_fp) vconreat_fp, "
            lstrSql = lstrSql & "       SUM(vdemreat_p) vdemreat_p, "
            lstrSql = lstrSql & "       SUM(vdemreat_fp) vdemreat_fp, "

            'Micro geração
            'lstrSql = lstrSql & "       SUM(qkwh_reverso) qkwh_reverso, "
            'lstrSql = lstrSql & "       SUM(vkwh_reverso) vkwh_reverso, "
            lstrSql = lstrSql & "       SUM(qkwh_reversop) qkwh_reversop, "
            lstrSql = lstrSql & "       SUM(qkwh_reversoi) qkwh_reversoi, "
            lstrSql = lstrSql & "       SUM(qkwh_reversofp) qkwh_reversofp, "
            lstrSql = lstrSql & "       SUM(vkwh_reversop) vkwh_reversop, "
            lstrSql = lstrSql & "       SUM(vkwh_reversoi) vkwh_reversoi, "
            lstrSql = lstrSql & "       SUM(vkwh_reversofp) vkwh_reversofp, "
            lstrSql = lstrSql & "       SUM(vkwh_reverso_importe) vkwh_reverso_importe, "

            '
            lstrSql = lstrSql & "       SUM(qkwh_reversop_sefaz) qkwh_reversop_sefaz, "
            lstrSql = lstrSql & "       SUM(qkwh_reversoi_sefaz) qkwh_reversoi_sefaz, "
            lstrSql = lstrSql & "       SUM(qkwh_reversofp_sefaz) qkwh_reversofp_sefaz, "
            lstrSql = lstrSql & "       SUM(vkwh_reversop_sefaz) vkwh_reversop_sefaz, "
            lstrSql = lstrSql & "       SUM(vkwh_reversoi_sefaz) vkwh_reversoi_sefaz, "
            lstrSql = lstrSql & "       SUM(vkwh_reversofp_sefaz) vkwh_reversofp_sefaz, "

            'Tributação
            lstrSql = lstrSql & "       SUM(icms) icms, "
            lstrSql = lstrSql & "       SUM(pis) pis, "
            lstrSql = lstrSql & "       SUM(cofins) cofins, "
            lstrSql = lstrSql & "       SUM(baseicms) baseicms, "
            lstrSql = lstrSql & "       SUM(basepis) basepis, "
            lstrSql = lstrSql & "       SUM(basecofins) basecofins, "
            lstrSql = lstrSql & "       SUM(icmspiscof) icmspiscof, "
            lstrSql = lstrSql & "       SUM(isentoicms) isentoicms, "
            lstrSql = lstrSql & "       SUM(diferido) diferido, "

            'Tributação - Substituição tributária
            lstrSql = lstrSql & "       SUM(icms_st) icms_st, "
            lstrSql = lstrSql & "       SUM(pis_st) pis_st, "
            lstrSql = lstrSql & "       SUM(cofins_st) cofins_st, "

            'Outros
            lstrSql = lstrSql & "       SUM(tip) tip, "
            lstrSql = lstrSql & "       SUM(sld_arred) sld_arred, "
            lstrSql = lstrSql & "       SUM(enc_finan) enc_finan, "
            lstrSql = lstrSql & "       SUM(dif_eltrbr) dif_eltrbr, "
            lstrSql = lstrSql & "       SUM(juros) juros, "
            lstrSql = lstrSql & "       SUM(encargo) encargo, "
            lstrSql = lstrSql & "       SUM(must) must, "
            lstrSql = lstrSql & "       SUM(convenios) convenios, "
            lstrSql = lstrSql & "       SUM(descontos) descontos, "
            lstrSql = lstrSql & "       SUM(descontos_1) descontos_1, "
            lstrSql = lstrSql & "       SUM(retencao) retencao, "
            lstrSql = lstrSql & "       SUM(diversos) diversos, "
            lstrSql = lstrSql & "       SUM(taxados) taxados, "
            lstrSql = lstrSql & "       SUM(total) total "

            If astrGrupo = "AB" Then
                lstrSql0 = ", IF(LEFT(grupot,1)='B','B',grupot) grupot "
            ElseIf astrGrupo = "AL" Then
                lstrSql0 = ", grupo "
            Else
                lstrSql0 = ", IF(LEFT(grupot,1)='B','B',grupo) grupo "
            End If

            lstrSql1 = " FROM " & istrTabTemp & " WHERE 1 = 1 AND "

            If Me.cmbModelo.SelectedIndex = 1 Then
                lstrSql1 = lstrSql1 & " zona = '" & astrZona & "' AND "
            End If

            ' Retirado Everton
            If astrGrupo <> "AB" Then

                If astrGrupo = "AL" Then
                    lstrSql1 = lstrSql1 & "LEFT(grupo,2) = '" & Microsoft.VisualBasic.Left(astrGrupo, 2) & "' AND " ' Pode ser AL(livre) ou ALS(livre especial)
                Else
                    If astrGrupo = "A" Then
                        lstrSql1 = lstrSql1 & "LEFT(grupo,1) = '" & Microsoft.VisualBasic.Left(astrGrupo, 1) & "' AND " 'LEFT(grupo,2) <> 'AL' AND "
                    Else
                        lstrSql1 = lstrSql1 & "LEFT(grupo,1) = '" & Microsoft.VisualBasic.Left(astrGrupo, 1) & "' AND "
                    End If
                End If

            End If

            If astrGrupo = "AB" Then
                'lstrSql3 = " GROUP BY grupot ASC "
            ElseIf astrGrupo = "A" Then
                'lstrSql3 = " GROUP BY grupo ASC "
            ElseIf astrGrupo = "B" Then
                'lstrSql3 = " GROUP BY LEFT(grupo,1) ASC "
            ElseIf astrGrupo = "AL" Then
                'lstrSql3 = "GROUP BY LEFT(grupo,4) ASC "
                'lstrSql3 = lstrSql3 & "ORDER BY sequencia"
            End If




            ' ************ OS TOTAIS FORAM SOLICITADOS PELO DIR. DANIEL PARA VIREM PRIMEIRO ************************************************************************************************** 
            'TOTAL GERAL ASSOCIADOS
            If cmbTipo.SelectedIndex = 1 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - Total Geral Associados "
                    Me.lblInfo.Refresh()

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 7000 AND 7999 AND LEFT(classe,2) <> '72' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = " matricula > 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "TOTAL GERAL ASSOCIADOS ", row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If

            'TOTAL GERAL NÃO ASSOCIADOS
            If cmbTipo.SelectedIndex = 2 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - Total Geral Não Associados "
                    Me.lblInfo.Refresh()

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 7000 AND 7999 AND LEFT(classe,2) <> '72' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = " matricula <= 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "TOTAL GERAL NÃO ASSOCIADOS", row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If

            'TOTAL GERAL ASSOCIADOS + NÃO ASSOCIADOS
            If cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - Total Geral Associados + Não Associados "
                    Me.lblInfo.Refresh()

                    sTextoTotalAssociados = ""

                    If cmbTipo.SelectedIndex = 0 Then
                        sTextoTotalAssociados = "TOTAL GERAL ASSOCIADOS + NÃO ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 1 Then
                        sTextoTotalAssociados = "TOTAL GERAL ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 2 Then
                        sTextoTotalAssociados = "TOTAL GERAL NÃO ASSOCIADOS"
                    End If

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 7000 AND 7999 AND LEFT(classe,2) <> '72' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = " matricula is not null"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, sTextoTotalAssociados, row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If
            ' ************ FIM DOS TOTAIS ************************************************************************************************** 



            ' ************ INICIO DAS CONSULTAS PARA POPULAR AS TABELAS ************************************************************************************************** 
            ' RESIDENCIAL
            If cmbTipo.SelectedIndex = 1 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    lblnCanRE = False

                    Me.lblInfo.Text = lstrAux & " - Residencial ASSOCIADOS "
                    Me.lblInfo.Refresh()


                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    ' lstrSql2 = " classe = 9101 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">", "<") & " 0 "
                    lstrSql2 = " classe BETWEEN 9000 AND 9999 and matricula> 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then
                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "RESIDENCIAL ASSOCIADOS", astrGrupo,  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If


            ' RESIDENCIAL NÃO ASSOCIADOS
            If cmbTipo.SelectedIndex = 2 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    lblnCanRE = False

                    Me.lblInfo.Text = lstrAux & " - Residencial NÃO ASSOCIADOS "
                    Me.lblInfo.Refresh()

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    ' lstrSql2 = " classe = 9101 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">", "<") & " 0 "
                    lstrSql2 = " classe BETWEEN 9000 AND 9999 and matricula <= 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then
                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "RESIDENCIAL NÃO ASSOCIADOS", astrGrupo,  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If


            ' TOTAL RESIDENCIAL
            If cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    lblnCanRE = False

                    Me.lblInfo.Text = lstrAux & " - Total Residencial Associados + Não Associados"
                    Me.lblInfo.Refresh()

                    sTextoTotalAssociados = ""

                    If cmbTipo.SelectedIndex = 0 Then
                        sTextoTotalAssociados = "TOTAL RESIDENCIAL ASSOCIADOS + NÃO ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 1 Then
                        sTextoTotalAssociados = "TOTAL RESIDENCIAL ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 2 Then
                        sTextoTotalAssociados = "TOTAL RESIDENCIAL NÃO ASSOCIADOS"
                    End If

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    ' lstrSql2 = " classe = 9101 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">", "<") & " 0 "
                    lstrSql2 = " classe BETWEEN 9000 AND 9999"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then
                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, sTextoTotalAssociados, astrGrupo,  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If



            ' INDUSTRIAL 
            If cmbTipo.SelectedIndex = 1 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - Industrial ASSOCIADOS "
                    Me.lblInfo.Refresh()

                    'INDUSTRIAL (1,2,3)

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 0 AND 3999 AND classe <> '0100' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 0 AND 3999 AND  matricula > 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql1 & lstrSql2 & lstrSql3
                    'objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql2
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)


                    If dt.Rows.Count <> 0 Then
                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "INDUSTRIAL ASSOCIADOS ", row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next

                    End If

                End If
            End If


            If cmbTipo.SelectedIndex = 2 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - Industrial NÃO ASSOCIADOS "
                    Me.lblInfo.Refresh()

                    'INDUSTRIAL (1,2,3)

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 0 AND 3999 AND classe <> '0100' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 1 AND 3999 AND  matricula <= 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql1 & lstrSql2 & lstrSql3
                    'objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql2
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then
                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "INDUSTRIAL NÃO ASSOCIADOS ", row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If


                End If
            End If

            If cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - Total Industrial ASSOCIADOS + NÃO ASSOCIADOS "
                    Me.lblInfo.Refresh()

                    sTextoTotalAssociados = ""

                    If cmbTipo.SelectedIndex = 0 Then
                        sTextoTotalAssociados = "TOTAL INDUSTRIAL ASSOCIADOS + NÃO ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 1 Then
                        sTextoTotalAssociados = "TOTAL INDUSTRIAL ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 2 Then
                        sTextoTotalAssociados = "TOTAL INDUSTRIAL NÃO ASSOCIADOS"
                    End If

                    'INDUSTRIAL (1,2,3)

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 0 AND 3999 AND classe <> '0100' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 1 AND 3999"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql1 & lstrSql2 & lstrSql3
                    'objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql2
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then
                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, sTextoTotalAssociados, row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If


                End If
            End If


            ' COMERCIAL
            If cmbTipo.SelectedIndex = 1 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - Comercial ASSOCIADOS "
                    Me.lblInfo.Refresh()

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 4000 AND 4999 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 4000 AND 4999 AND matricula > 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows

                            If row("ncons") > 0 Then
                                Imprime(row, "COMERCIAL ASSOCIADOS", row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If

                        Next
                    End If

                End If
            End If


            'COMERCIAL (4)
            If cmbTipo.SelectedIndex = 2 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - Comercial NÃO ASSOCIADOS "
                    Me.lblInfo.Refresh()


                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 4000 AND 4999 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 4000 AND 4999 AND matricula <= 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows

                            If row("ncons") > 0 Then
                                Imprime(row, "COMERCIAL NÃO ASSOCIADOS", row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If

                        Next
                    End If

                End If
            End If


            'COMERCIAL (4)
            If cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - Total Comercial ASSOCIADOS + NÃO ASSOCIADOS "
                    Me.lblInfo.Refresh()

                    sTextoTotalAssociados = ""

                    If cmbTipo.SelectedIndex = 0 Then
                        sTextoTotalAssociados = "TOTAL COMERCIAL ASSOCIADOS + NÃO ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 1 Then
                        sTextoTotalAssociados = "TOTAL COMERCIAL ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 2 Then
                        sTextoTotalAssociados = "TOTAL COMERCIAL NÃO ASSOCIADOS"
                    End If


                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 4000 AND 4999 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 4000 AND 4999"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows

                            If row("ncons") > 0 Then
                                Imprime(row, sTextoTotalAssociados, row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If

                        Next
                    End If

                End If
            End If

            'RURAL (5)
            If cmbTipo.SelectedIndex = 1 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - Rural ASSOCIADOS "
                    Me.lblInfo.Refresh()

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 5000 AND 5999 AND irrigacao_aquicultura = 0 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 5000 AND 5999 AND matricula > 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "RURAL ASSOCIADOS", row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next

                    End If

                End If
            End If


            'RURAL (5)
            If cmbTipo.SelectedIndex = 2 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - Rural NÃO ASSOCIADOS "
                    Me.lblInfo.Refresh()

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 5000 AND 5999 AND irrigacao_aquicultura = 0 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 5000 AND 5999 AND matricula <= 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "RURAL NÃO ASSOCIADOS", row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next

                    End If

                End If
            End If


            'RURAL (5)
            If cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - Total Rural ASSOCIADOS + NÃO ASSOCIADOS "
                    Me.lblInfo.Refresh()

                    sTextoTotalAssociados = ""

                    If cmbTipo.SelectedIndex = 0 Then
                        sTextoTotalAssociados = "TOTAL RURAL ASSOCIADOS + NÃO ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 1 Then
                        sTextoTotalAssociados = "TOTAL RURAL ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 2 Then
                        sTextoTotalAssociados = "TOTAL RURAL NÃO ASSOCIADOS"
                    End If

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 5000 AND 5999 AND irrigacao_aquicultura = 0 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 5000 AND 5999"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, sTextoTotalAssociados, row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next

                    End If

                End If
            End If


            If cmbTipo.SelectedIndex = 1 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    'TOTAL PODER PUBLICO (61,62,63)
                    Me.lblInfo.Text = lstrAux & " - Poder Público "
                    Me.lblInfo.Refresh()


                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 6100 AND 6399 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 6000 AND 6399 AND matricula > 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql1 & lstrSql2
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "PODER PÚBLICO ASSOCIADOS", astrGrupo,  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If


            If cmbTipo.SelectedIndex = 2 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    'TOTAL PODER PUBLICO (61,62,63)
                    Me.lblInfo.Text = lstrAux & " - Poder Público "
                    Me.lblInfo.Refresh()


                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 6100 AND 6399 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 6000 AND 6399 AND matricula <= 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql1 & lstrSql2
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "PODER PÚBLICO NÃO ASSOCIADOS", astrGrupo,  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If


            If cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    'TOTAL PODER PUBLICO (61,62,63)
                    Me.lblInfo.Text = lstrAux & " - Total Poder Público "
                    Me.lblInfo.Refresh()

                    sTextoTotalAssociados = ""

                    If cmbTipo.SelectedIndex = 0 Then
                        sTextoTotalAssociados = "TOTAL PODER PÚBLICO ASSOCIADOS + NÃO ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 1 Then
                        sTextoTotalAssociados = "TOTAL PODER PÚBLICO ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 2 Then
                        sTextoTotalAssociados = "TOTAL PODER PÚBLICO NÃO ASSOCIADOS"
                    End If


                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 6100 AND 6399 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 6000 AND 6399"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql1 & lstrSql2
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "TOTAL PODER PÚBLICO ASSOCIADOS + NÃO ASSOCIADOS", astrGrupo,  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If


            'ILUMINAÇÃO PUBLICA (6401)
            If cmbTipo.SelectedIndex = 1 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - IP "
                    Me.lblInfo.Refresh()

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe = 6401 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 6400 AND 6499 AND matricula > 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql1 & lstrSql2
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "ILUMINAÇÃO PÚBLICA ASSOCIADOS", astrGrupo,  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If


            'ILUMINAÇÃO PUBLICA (6401)
            If cmbTipo.SelectedIndex = 2 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - IP "
                    Me.lblInfo.Refresh()

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe = 6401 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 6400 AND 6499 AND matricula <= 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql1 & lstrSql2
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows

                            If row("ncons") > 0 Then
                                Imprime(row, "ILUMINAÇÃO PÚBLICA NÃO ASSOCIADOS", astrGrupo,  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If


            'TOTAL ILUMINAÇÃO PUBLICA (6401)
            If cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " -TOTAL IP "
                    Me.lblInfo.Refresh()

                    sTextoTotalAssociados = ""

                    If cmbTipo.SelectedIndex = 0 Then
                        sTextoTotalAssociados = "TOTAL ILUMINAÇÃO PÚBLICA ASSOCIADOS + NÃO ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 1 Then
                        sTextoTotalAssociados = "TOTAL ILUMINAÇÃO PÚBLICA ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 2 Then
                        sTextoTotalAssociados = "TOTAL ILUMINAÇÃO PÚBLICA NÃO ASSOCIADOS"
                    End If

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe = 6401 AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 6400 AND 6499"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql1 & lstrSql2
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows

                            If row("ncons") > 0 Then
                                Imprime(row, sTextoTotalAssociados, astrGrupo,  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If


            'SERVIÇO PUBLICO (7)
            If cmbTipo.SelectedIndex = 1 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - SP "
                    Me.lblInfo.Refresh()

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 7000 AND 7999 AND LEFT(classe,2) <> '72' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 7000 AND 7999 AND matricula > 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then
                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "SERVIÇO PÚBLICO ASSOCIADOS" & IIf(lintAux = 1, " (C)", " "), row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If

            'SERVIÇO PUBLICO (7)
            If cmbTipo.SelectedIndex = 2 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - SP "
                    Me.lblInfo.Refresh()

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 7000 AND 7999 AND LEFT(classe,2) <> '72' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 7000 AND 7999 AND matricula <= 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then
                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "SERVIÇO PÚBLICO NÃO ASSOCIADOS" & IIf(lintAux = 1, " (C)", " "), row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If



            'SERVIÇO PUBLICO (7)
            If cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - TOTAL SP "
                    Me.lblInfo.Refresh()


                    sTextoTotalAssociados = ""

                    If cmbTipo.SelectedIndex = 0 Then
                        sTextoTotalAssociados = "TOTAL SERVIÇO PÚBLICO ASSOCIADOS + NÃO ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 1 Then
                        sTextoTotalAssociados = "TOTAL SERVIÇO PÚBLICO ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 2 Then
                        sTextoTotalAssociados = "TOTAL SERVIÇO PÚBLICO NÃO ASSOCIADOS"
                    End If

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 7000 AND 7999 AND LEFT(classe,2) <> '72' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 7000 AND 7999"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then
                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, sTextoTotalAssociados & IIf(lintAux = 1, " (C)", " "), row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If

                End If
            End If


            'CONSUMO PRÓPRIO
            If cmbTipo.SelectedIndex = 1 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - CP "
                    Me.lblInfo.Refresh()

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 7000 AND 7999 AND LEFT(classe,2) <> '72' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 8000 AND 8999 AND matricula > 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "CONSUMO PRÓPRIO ASSOCIADOS", row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If


                End If
            End If

            'CONSUMO PRÓPRIO NÂO ASSOCIADOS
            If cmbTipo.SelectedIndex = 2 Or cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " - CP "
                    Me.lblInfo.Refresh()


                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 7000 AND 7999 AND LEFT(classe,2) <> '72' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 8000 AND 8999 AND matricula <= 0"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, "CONSUMO PRÓPRIO NÃO ASSOCIADOS", row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If


                End If
            End If

            'CONSUMO PRÓPRIO NÂO ASSOCIADOS
            If cmbTipo.SelectedIndex = 0 Then
                If Not iblnTotalizado Then

                    Me.lblInfo.Text = lstrAux & " -TOTAL CP "
                    Me.lblInfo.Refresh()

                    sTextoTotalAssociados = ""

                    If cmbTipo.SelectedIndex = 0 Then
                        sTextoTotalAssociados = "TOTAL CONSUMO PRÓPRIO ASSOCIADOS + NÃO ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 1 Then
                        sTextoTotalAssociados = "TOTAL CONSUMO PRÓPRIO ASSOCIADOS"
                    ElseIf cmbTipo.SelectedIndex = 2 Then
                        sTextoTotalAssociados = "TOTAL CONSUMO PRÓPRIO NÃO ASSOCIADOS"
                    End If

                    lstrSqlP = ""
                    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
                    'lstrSql2 = "classe BETWEEN 7000 AND 7999 AND LEFT(classe,2) <> '72' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
                    lstrSql2 = "classe BETWEEN 8000 AND 8999"

                    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
                    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

                    If dt.Rows.Count <> 0 Then

                        For Each row As DataRow In dt.Rows
                            If row("ncons") > 0 Then
                                Imprime(row, sTextoTotalAssociados, row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
                            End If
                        Next
                    End If


                End If
            End If

            ''TOTAL GERAL ASSOCIADOS
            'If Not iblnTotalizado Then

            '    Me.lblInfo.Text = lstrAux & " - Total Geral Associados "
            '    Me.lblInfo.Refresh()

            '    lstrSqlP = ""
            '    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
            '    'lstrSql2 = "classe BETWEEN 7000 AND 7999 AND LEFT(classe,2) <> '72' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
            '    lstrSql2 = " matricula > 0"

            '    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
            '    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

            '    If dt.Rows.Count <> 0 Then

            '        For Each row As DataRow In dt.Rows
            '            If row("ncons") > 0 Then
            '                Imprime(row, "TOTAL GERAL ASSOCIADOS", row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
            '            End If
            '        Next
            '    End If

            'End If


            ''TOTAL GERAL NÃO ASSOCIADOS
            'If Not iblnTotalizado Then

            '    Me.lblInfo.Text = lstrAux & " - Total Geral Não Associados "
            '    Me.lblInfo.Refresh()

            '    lstrSqlP = ""
            '    lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
            '    'lstrSql2 = "classe BETWEEN 7000 AND 7999 AND LEFT(classe,2) <> '72' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
            '    lstrSql2 = " matricula <= 0"

            '    objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
            '    dt = repositorioTempEstatis.Execute_2(objTempEstatis)

            '    If dt.Rows.Count <> 0 Then

            '        For Each row As DataRow In dt.Rows
            '            If row("ncons") > 0 Then
            '                Imprime(row, "TOTAL GERAL NÃO ASSOCIADOS", row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
            '            End If
            '        Next
            '    End If

            'End If


            ''TOTAL GERAL ASSOCIADOS + NÃO ASSOCIADOS
            'If Not iblnTotalizado Then

            '        Me.lblInfo.Text = lstrAux & " - Total Geral Associados + Não Associados "
            '        Me.lblInfo.Refresh()

            '        lstrSqlP = ""
            '        lstrSqlP = lstrSqlP & "SELECT COUNT(*) ncons, grupo, grupot, "
            '        'lstrSql2 = "classe BETWEEN 7000 AND 7999 AND LEFT(classe,2) <> '72' AND (qkwh_fat+qkwh_fat_p+qkwh_fat_i+qkwh_fat_fp) " & IIf(lintAux = 0, ">=", "<") & " 0 "
            '        lstrSql2 = " matricula is not null"

            '        objTempEstatis.TABLE = lstrSqlP & lstrSql & lstrSql0 & lstrSql1 & lstrSql2 & lstrSql3
            '        dt = repositorioTempEstatis.Execute_2(objTempEstatis)

            '        If dt.Rows.Count <> 0 Then

            '            For Each row As DataRow In dt.Rows
            '                If row("ncons") > 0 Then
            '                    Imprime(row, "TOTAL GERAL ASSOCIADOS + NÃO ASSOCIADOS", row("grupo"),  , "T", astrGrupo, astrCabecTitulo, astrCabecGrupo)
            '                End If
            '            Next
            '        End If

            '    End If



        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: RelEstat_Operacional" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub Imprime(ByRef row As DataRow, ByVal tit As String, ByVal astrGrupo As String, Optional ByVal astrFase As String = "", Optional ByVal astrTipo As String = "", Optional ByVal astrGrpImp As String = "", Optional ByVal astrCabecTitulo As String = "", Optional ByVal astrCabecGrupo As String = "")

        Dim strTamCol As String
        Dim strTemp As String
        Dim ldblNCons As Double
        Dim ldblQKwhCons As Double
        Dim ldblQKwhFat As Double
        Dim ldblQKwhFatBan As Double
        Dim ldblQKwContr As Double
        Dim ldblQKwFat As Double
        Dim ldblQKwDifFat As Double
        Dim ldblVKwhCons As Double
        Dim ldblVKwhFat As Double
        Dim ldblVKwhFatBan As Double
        Dim ldblVKwFat As Double
        Dim ldblVConReat As Double
        Dim ldblVDemReat As Double
        Dim ldblQKwhFatp As Double
        Dim ldblQKwhFati As Double
        Dim ldblQKwhFatfp As Double
        Dim ldblQKwhFatpBan As Double
        Dim ldblQKwhFatiBan As Double
        Dim ldblQKwhFatfpBan As Double
        Dim ldblQKwhFatpLiv As Double
        Dim ldblQKwhFatfpLiv As Double
        Dim ldblQKwhDevp As Double
        Dim ldblQKwhDevfp As Double
        Dim ldblQKwhUtrp As Double
        Dim ldblQKwhUtrfp As Double
        Dim ldblQKwContrp As Double
        Dim ldblQKwContrfp As Double
        Dim ldblQKwFatp As Double
        Dim ldblQKwFatfp As Double
        Dim ldblQKwDifFatp As Double
        Dim ldblQKwDifFatfp As Double
        Dim ldblQKwFatUp As Double
        Dim ldblQKwFatUfp As Double
        Dim ldblVKwhFatp As Double
        Dim ldblVKwhFati As Double
        Dim ldblVKwhFatfp As Double
        Dim ldblVKwhFatpBan As Double
        Dim ldblVKwhFatiBan As Double
        Dim ldblVKwhFatfpBan As Double
        Dim ldblVKwhFatpLiv As Double
        Dim ldblVKwhFatfpLiv As Double
        Dim ldblVKwhDevp As Double
        Dim ldblVKwhDevfp As Double
        Dim ldblVKwhUtrp As Double
        Dim ldblVKwhUtrfp As Double
        Dim ldblVKwFatp As Double
        Dim ldblVKwFatfp As Double
        Dim ldblVKwDifFatp As Double
        Dim ldblVKwDifFatfp As Double
        Dim ldblVKwFatUp As Double
        Dim ldblVKwFatUfp As Double
        '
        Dim ldblVkwDscProv As Double
        Dim ldblVkwDscReal As Double
        Dim ldblVkwDevCcee As Double
        Dim ldblVkwCobCcee As Double
        '
        Dim ldblVkwhDscProv As Double
        Dim ldblVkwhDscReal As Double
        Dim ldblVkwhDevCcee As Double
        Dim ldblVkwhCobCcee As Double
        '
        Dim ldblVConReatp As Double
        Dim ldblVConReatfp As Double
        Dim ldblVDemReatp As Double
        Dim ldblVDemReatfp As Double
        'Micro geração
        'Dim ldblQKwhReverso As Double
        'Dim ldblVKwhReverso As Double
        Dim ldblQKwhReversop As Double
        Dim ldblQKwhReversoi As Double
        Dim ldblQKwhReversofp As Double
        Dim ldblQKwhReversotot As Double
        Dim ldblVKwhReversop As Double
        Dim ldblVKwhReversoi As Double
        Dim ldblVKwhReversofp As Double
        Dim ldblVKwhReversotot As Double
        '
        Dim ldblQKwhReversop_sefaz As Double
        Dim ldblQKwhReversoi_sefaz As Double
        Dim ldblQKwhReversofp_sefaz As Double
        Dim ldblQKwhReversotot_sefaz As Double
        Dim ldblVKwhReversop_sefaz As Double
        Dim ldblVKwhReversoi_sefaz As Double
        Dim ldblVKwhReversofp_sefaz As Double
        Dim ldblVKwhReversotot_sefaz As Double
        '
        Dim ldblVkwhReversoImporte As Double
        '
        Dim ldblTip As Double
        Dim ldblSldArred As Double
        Dim ldblEncFinan As Double
        Dim ldblIcms As Double
        Dim ldblPis As Double
        Dim ldblCofins As Double
        Dim ldblIcmsSt As Double
        Dim ldblPisSt As Double
        Dim ldblCofinsSt As Double
        Dim ldblBaseIcms As Double
        Dim ldblBasePis As Double
        Dim ldblBaseCofins As Double
        Dim ldblIcmsPisCof As Double
        Dim ldblIsentoIcms As Double
        Dim ldblDiferido As Double
        Dim ldblDifEltrbr As Double
        Dim ldblJuros As Double
        Dim ldblMulta As Double
        Dim ldblEncargo As Double
        Dim ldblMust As Double
        Dim ldblTotal As Double
        Dim ldblTaxados As Double
        Dim ldblDiversos As Double
        Dim ldblConvenios As Double
        Dim ldblDescontos As Double
        Dim ldblDescontos_1 As Double
        Dim ldblRetencao As Double
        '
        Dim ldblReceitaCompanhia As Double
        Dim ldblImporte As Double

        Dim bytBLOBData() As Byte

        Dim vlist

        Dim objEmpresa As New entidadeEmpresa
        Dim repositorioEmpresa As New repositorioEmpresa

        Try

            LimpaCols()

            ldblNCons = CDbl(IIf(IsDBNull(row("ncons")), 0, row("ncons")))
            ldblQKwhCons = CDbl(IIf(IsDBNull(row("qkwh_cons")), 0, row("qkwh_cons")))
            ldblQKwhFat = CDbl(IIf(IsDBNull(row("qkwh_fat")), 0, row("qkwh_fat")))
            ldblQKwhFatBan = CDbl(IIf(IsDBNull(row("qkwh_fat_ban")), 0, row("qkwh_fat_ban")))
            'ldblQkwContr = Conversion.CDbl(IIf(IsNull(row("qkw_contr")), 0, row("qkw_contr")))
            ldblQKwFat = CDbl(IIf(IsDBNull(row("qkw_fat")), 0, row("qkw_fat")))
            ldblVKwhCons = CDbl(IIf(IsDBNull(row("vkwh_cons")), 0, row("vkwh_cons")))
            ldblVKwhFat = CDbl(IIf(IsDBNull(row("vkwh_fat")), 0, row("vkwh_fat")))
            ldblVKwhFatBan = CDbl(IIf(IsDBNull(row("vkwh_fat_ban")), 0, row("vkwh_fat_ban")))
            ldblVKwFat = CDbl(IIf(IsDBNull(row("vkw_fat")), 0, row("vkw_fat")))
            ldblVConReat = CDbl(IIf(IsDBNull(row("vconreat")), 0, row("vconreat")))
            ldblVDemReat = CDbl(IIf(IsDBNull(row("vdemreat")), 0, row("vdemreat")))
            ldblQKwhFatp = CDbl(IIf(IsDBNull(row("qkwh_fat_p")), 0, row("qkwh_fat_p")))
            ldblQKwhFati = CDbl(IIf(IsDBNull(row("qkwh_fat_i")), 0, row("qkwh_fat_i")))
            ldblQKwhFatfp = CDbl(IIf(IsDBNull(row("qkwh_fat_fp")), 0, row("qkwh_fat_fp")))
            ldblQKwhFatpBan = CDbl(IIf(IsDBNull(row("qkwh_fat_p_ban")), 0, row("qkwh_fat_p_ban")))
            ldblQKwhFatiBan = CDbl(IIf(IsDBNull(row("qkwh_fat_i_ban")), 0, row("qkwh_fat_i_ban")))
            ldblQKwhFatfpBan = CDbl(IIf(IsDBNull(row("qkwh_fat_fp_ban")), 0, row("qkwh_fat_fp_ban")))
            ldblQKwhFatpLiv = CDbl(IIf(IsDBNull(row("qkwh_fat_p_liv")), 0, row("qkwh_fat_p_liv")))
            ldblQKwhFatfpLiv = CDbl(IIf(IsDBNull(row("qkwh_fat_fp_liv")), 0, row("qkwh_fat_fp_liv")))
            ldblQKwhDevp = CDbl(IIf(IsDBNull(row("qkwh_dev_p")), 0, row("qkwh_dev_p")))
            ldblQKwhDevfp = CDbl(IIf(IsDBNull(row("qkwh_dev_fp")), 0, row("qkwh_dev_fp")))
            ldblQKwhUtrp = CDbl(IIf(IsDBNull(row("qkwh_utr_p")), 0, row("qkwh_utr_p")))
            ldblQKwhUtrfp = CDbl(IIf(IsDBNull(row("qkwh_utr_fp")), 0, row("qkwh_utr_fp")))
            'ldblQkwContrp = Conversion.CDbl(IIf(IsNull(row("qkw_contr_p")), 0, row("qkw_contr_p")))
            'ldblQkwContrfp = Conversion.CDbl(IIf(IsNull(row("qkw_contr_fp")), 0, row("qkw_contr_fp")))
            ldblQKwFatp = CDbl(IIf(IsDBNull(row("qkw_fat_p")), 0, row("qkw_fat_p")))
            ldblQKwFatfp = CDbl(IIf(IsDBNull(row("qkw_fat_fp")), 0, row("qkw_fat_fp")))
            ' Arlindo dif. demanda
            ldblQKwDifFatp = CDbl(IIf(IsDBNull(row("qkw_dif_fat_p")), 0, row("qkw_dif_fat_p")))
            ldblQKwDifFatfp = CDbl(IIf(IsDBNull(row("qkw_dif_fat_fp")), 0, row("qkw_dif_fat_fp")))
            ldblQKwFatUp = CDbl(IIf(IsDBNull(row("qkw_fatu_p")), 0, row("qkw_fatu_p")))
            ldblQKwFatUfp = CDbl(IIf(IsDBNull(row("qkw_fatu_fp")), 0, row("qkw_fatu_fp")))
            ldblVKwhFatp = CDbl(IIf(IsDBNull(row("vkwh_fat_p")), 0, row("vkwh_fat_p")))
            ldblVKwhFati = CDbl(IIf(IsDBNull(row("vkwh_fat_i")), 0, row("vkwh_fat_i")))
            ldblVKwhFatfp = CDbl(IIf(IsDBNull(row("vkwh_fat_fp")), 0, row("vkwh_fat_fp")))
            ldblVKwhFatpBan = CDbl(IIf(IsDBNull(row("vkwh_fat_p_ban")), 0, row("vkwh_fat_p_ban")))
            ldblVKwhFatiBan = CDbl(IIf(IsDBNull(row("vkwh_fat_i_ban")), 0, row("vkwh_fat_i_ban")))
            ldblVKwhFatfpBan = CDbl(IIf(IsDBNull(row("vkwh_fat_fp_ban")), 0, row("vkwh_fat_fp_ban")))
            ldblVKwhFatpLiv = CDbl(IIf(IsDBNull(row("vkwh_fat_p_liv")), 0, row("vkwh_fat_p_liv")))
            ldblVKwhFatfpLiv = CDbl(IIf(IsDBNull(row("vkwh_fat_fp_liv")), 0, row("vkwh_fat_fp_liv")))
            ldblVKwhDevp = CDbl(IIf(IsDBNull(row("vkwh_dev_p")), 0, row("vkwh_dev_p")))
            ldblVKwhDevfp = CDbl(IIf(IsDBNull(row("vkwh_dev_fp")), 0, row("vkwh_dev_fp")))
            ldblVKwhUtrp = CDbl(IIf(IsDBNull(row("vkwh_utr_p")), 0, row("vkwh_utr_p")))
            ldblVKwhUtrfp = CDbl(IIf(IsDBNull(row("vkwh_utr_fp")), 0, row("vkwh_utr_fp")))
            ldblVKwFatp = CDbl(IIf(IsDBNull(row("vkw_fat_p")), 0, row("vkw_fat_p")))
            ldblVKwFatfp = CDbl(IIf(IsDBNull(row("vkw_fat_fp")), 0, row("vkw_fat_fp")))
            ' Arlindo dif. demanda
            ldblVKwDifFatp = CDbl(IIf(IsDBNull(row("vkw_dif_fat_p")), 0, row("vkw_dif_fat_p")))
            ldblVKwDifFatfp = CDbl(IIf(IsDBNull(row("vkw_dif_fat_fp")), 0, row("vkw_dif_fat_fp")))
            ldblVKwFatUp = CDbl(IIf(IsDBNull(row("vkw_fatu_p")), 0, row("vkw_fatu_p")))
            ldblVKwFatUfp = CDbl(IIf(IsDBNull(row("vkw_fatu_fp")), 0, row("vkw_fatu_fp")))
            ldblVkwDscProv = CDbl(IIf(IsDBNull(row("vkw_dsc_prov")), 0, row("vkw_dsc_prov")))
            ldblVkwDscReal = CDbl(IIf(IsDBNull(row("vkw_dsc_real")), 0, row("vkw_dsc_real")))
            ldblVkwDevCcee = CDbl(IIf(IsDBNull(row("vkw_dev_ccee")), 0, row("vkw_dev_ccee")))
            ldblVkwCobCcee = CDbl(IIf(IsDBNull(row("vkw_cob_ccee")), 0, row("vkw_cob_ccee")))
            ldblVkwhDscProv = CDbl(IIf(IsDBNull(row("vkwh_dsc_prov")), 0, row("vkwh_dsc_prov")))
            ldblVkwhDscReal = CDbl(IIf(IsDBNull(row("vkwh_dsc_real")), 0, row("vkwh_dsc_real")))
            ldblVkwhDevCcee = CDbl(IIf(IsDBNull(row("vkwh_dev_ccee")), 0, row("vkwh_dev_ccee")))
            ldblVkwhCobCcee = CDbl(IIf(IsDBNull(row("vkwh_cob_ccee")), 0, row("vkwh_cob_ccee")))
            ldblVConReatp = CDbl(IIf(IsDBNull(row("vconreat_p")), 0, row("vconreat_p")))
            ldblVConReatfp = CDbl(IIf(IsDBNull(row("vconreat_fp")), 0, row("vconreat_fp")))
            ldblVDemReatp = CDbl(IIf(IsDBNull(row("vdemreat_p")), 0, row("vdemreat_p")))
            ldblVDemReatfp = CDbl(IIf(IsDBNull(row("vdemreat_fp")), 0, row("vdemreat_fp")))
            'ldblQKwhReverso = Conversion.CDbl(IIf(IsNull(row("qkwh_reverso")), 0, row("qkwh_reverso")))
            'ldblVKwhReverso = Conversion.CDbl(IIf(IsNull(row("vkwh_reverso")), 0, row("vkwh_reverso")))
            ldblQKwhReversop = CDbl(IIf(IsDBNull(row("qkwh_reversop")), 0, row("qkwh_reversop")))
            ldblQKwhReversoi = CDbl(IIf(IsDBNull(row("qkwh_reversoi")), 0, row("qkwh_reversoi")))
            ldblQKwhReversofp = CDbl(IIf(IsDBNull(row("qkwh_reversofp")), 0, row("qkwh_reversofp")))
            ldblVKwhReversop = CDbl(IIf(IsDBNull(row("vkwh_reversop")), 0, row("vkwh_reversop")))
            ldblVKwhReversoi = CDbl(IIf(IsDBNull(row("vkwh_reversoi")), 0, row("vkwh_reversoi")))
            ldblVKwhReversofp = CDbl(IIf(IsDBNull(row("vkwh_reversofp")), 0, row("vkwh_reversofp")))
            ldblQKwhReversop_sefaz = CDbl(IIf(IsDBNull(row("qkwh_reversop_sefaz")), 0, row("qkwh_reversop_sefaz")))
            ldblQKwhReversoi_sefaz = CDbl(IIf(IsDBNull(row("qkwh_reversoi_sefaz")), 0, row("qkwh_reversoi_sefaz")))
            ldblQKwhReversofp_sefaz = CDbl(IIf(IsDBNull(row("qkwh_reversofp_sefaz")), 0, row("qkwh_reversofp_sefaz")))
            ldblVKwhReversop_sefaz = CDbl(IIf(IsDBNull(row("vkwh_reversop_sefaz")), 0, row("vkwh_reversop_sefaz")))
            ldblVKwhReversoi_sefaz = CDbl(IIf(IsDBNull(row("vkwh_reversoi_sefaz")), 0, row("vkwh_reversoi_sefaz")))
            ldblVKwhReversofp_sefaz = CDbl(IIf(IsDBNull(row("vkwh_reversofp_sefaz")), 0, row("vkwh_reversofp_sefaz")))
            ldblTip = CDbl(IIf(IsDBNull(row("tip")), 0, row("tip")))
            ldblSldArred = CDbl(IIf(IsDBNull(row("sld_arred")), 0, row("sld_arred")))
            ldblEncFinan = CDbl(IIf(IsDBNull(row("enc_finan")), 0, row("enc_finan")))
            ldblIcms = CDbl(IIf(IsDBNull(row("icms")), 0, row("icms")))
            ldblPis = CDbl(IIf(IsDBNull(row("pis")), 0, row("pis")))
            ldblCofins = CDbl(IIf(IsDBNull(row("cofins")), 0, row("cofins")))
            ldblIcmsSt = CDbl(IIf(IsDBNull(row("icms_st")), 0, row("icms_st")))
            ldblPisSt = CDbl(IIf(IsDBNull(row("pis_st")), 0, row("pis_st")))
            ldblCofinsSt = CDbl(IIf(IsDBNull(row("cofins_st")), 0, row("cofins_st")))
            ldblBaseIcms = CDbl(IIf(IsDBNull(row("baseicms")), 0, row("baseicms")))
            ldblBasePis = CDbl(IIf(IsDBNull(row("basepis")), 0, row("basepis")))
            ldblBaseCofins = CDbl(IIf(IsDBNull(row("basecofins")), 0, row("basecofins")))
            ldblIcmsPisCof = CDbl(IIf(IsDBNull(row("icmspiscof")), 0, row("icmspiscof")))
            ldblIsentoIcms = CDbl(IIf(IsDBNull(row("isentoicms")), 0, row("isentoicms")))
            ldblDiferido = CDbl(IIf(IsDBNull(row("diferido")), 0, row("diferido")))
            ldblDifEltrbr = CDbl(IIf(IsDBNull(row("dif_eltrbr")), 0, row("dif_eltrbr")))
            ldblJuros = CDbl(IIf(IsDBNull(row("juros")), 0, row("juros")))
            'ldblMulta = Conversion.CDbl(IIf(IsNull(row("multa")), 0, row("multa")))
            ldblEncargo = CDbl(IIf(IsDBNull(row("encargo")), 0, row("encargo")))
            ldblMust = CDbl(IIf(IsDBNull(row("must")), 0, row("must")))
            ldblTotal = CDbl(IIf(IsDBNull(row("total")), 0, row("total")))
            ldblTaxados = CDbl(IIf(IsDBNull(row("taxados")), 0, row("taxados")))
            ldblDiversos = CDbl(IIf(IsDBNull(row("diversos")), 0, row("diversos")))
            ldblConvenios = CDbl(IIf(IsDBNull(row("convenios")), 0, row("convenios")))
            ldblDescontos = CDbl(IIf(IsDBNull(row("descontos")), 0, row("descontos")))
            ldblDescontos_1 = CDbl(IIf(IsDBNull(row("descontos_1")), 0, row("descontos_1")))
            ldblRetencao = CDbl(IIf(IsDBNull(row("retencao")), 0, row("retencao")))
            ldblVkwhReversoImporte = CDbl(IIf(IsDBNull(row("vkwh_reverso_importe")), 0, row("vkwh_reverso_importe")))
            'ldblQKwhReversotot = Arredondar(ldblQKwhReverso,2) + Arredondar(ldblQKwhReversop,2) + Arredondar(ldblQKwhReversofp,2)
            'ldblVKwhReversotot = Arredondar(ldblVKwhReverso,2) + Arredondar(ldblVKwhReversop,2) + Arredondar(ldblVKwhReversofp,2)
            ldblQKwhReversotot = Arredondar(ldblQKwhReversop, 2) + Arredondar(ldblQKwhReversoi, 2) + Arredondar(ldblQKwhReversofp, 2)
            ldblVKwhReversotot = Arredondar(ldblVKwhReversop, 2) + Arredondar(ldblVKwhReversoi, 2) + Arredondar(ldblVKwhReversofp, 2)
            ldblQKwhReversotot_sefaz = Arredondar(ldblQKwhReversop_sefaz, 2) + Arredondar(ldblQKwhReversoi_sefaz, 2) + Arredondar(ldblQKwhReversofp_sefaz, 2)
            ldblVKwhReversotot_sefaz = Arredondar(ldblVKwhReversop_sefaz, 2) + Arredondar(ldblVKwhReversoi_sefaz, 2) + Arredondar(ldblVKwhReversofp_sefaz, 2)

            'Grupo 1
            If VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) = "01" And VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex) = "12" And Microsoft.VisualBasic.Left(Trim(astrGrupo), 2) = "AB" And lstrTotGeral = "TOTAL GERAL" Then
                strCol(1, 1) = "Nº CONSUMIDORES:"
                strCol(1, 2) = VB6.Format(llngNconsFimAno, "#,##0")
            Else
                strCol(1, 1) = "Nº CONSUMIDORES:"
                strCol(1, 2) = VB6.Format(ldblNCons, "#,##0")
            End If

            strCol(1, 3) = "Kwh CONSUMIDO:"
            strCol(1, 4) = VB6.Format(Arredondar(ldblQKwhCons, 3), "#,##0.00")
            strCol(1, 5) = "Kwh FATURADO:"
            strCol(1, 6) = VB6.Format(Arredondar(ldblQKwhFatp, 2) + Arredondar(ldblQKwhFati, 2) + Arredondar(ldblQKwhFatfp, 2) + Arredondar(ldblQKwhFat, 2) - (Arredondar(ldblQKwhDevp, 2) + Arredondar(ldblQKwhDevfp, 2)) + (Arredondar(ldblQKwhUtrp, 2) + Arredondar(ldblQKwhUtrfp, 2)), "#,##0.00")
            strCol(1, 7) = "Kwh FAT. PONTA:"
            strCol(1, 8) = VB6.Format(Arredondar(ldblQKwhFatp, 2) - Arredondar(ldblQKwhDevp, 2), "#,##0.00")
            strCol(1, 9) = "Kwh FAT. INTER:"
            strCol(1, 10) = VB6.Format(Arredondar(ldblQKwhFati, 2), "#,##0.00")
            strCol(1, 11) = "Kwh FAT. F.PONTA:"
            strCol(1, 12) = VB6.Format(Arredondar(ldblQKwhFatfp, 2) + Arredondar(ldblQKwhFat, 2) - Arredondar(ldblQKwhDevfp, 2), "#,##0.00")
            strCol(1, 13) = "Kw FATURADO:"
            strCol(1, 14) = VB6.Format(Arredondar(ldblQKwFatp, 2) + Arredondar(ldblQKwFatfp, 2) + Arredondar(ldblQKwFat, 2), "#,##0.00")
            strCol(1, 15) = "Kw FAT. PONTA:"
            strCol(1, 16) = VB6.Format(Arredondar(ldblQKwFatp, 2), "#,##0.00")
            strCol(1, 17) = "Kw FAT. F.PONTA:"
            strCol(1, 18) = VB6.Format(Arredondar(ldblQKwFatfp, 2) + Arredondar(ldblQKwFat, 2), "#,##0.00")
            ' Arlindo dif. demanda
            strCol(1, 19) = "Kw DIF. FATURADO:"
            strCol(1, 20) = VB6.Format(Arredondar(ldblQKwDifFatp, 2) + Arredondar(ldblQKwDifFatfp, 2), "#,##0.00")
            strCol(1, 21) = "Kw DIF. PONTA:"
            strCol(1, 22) = VB6.Format(Arredondar(ldblQKwDifFatp, 2), "#,##0.00")
            strCol(1, 23) = "Kw DIF. F.PONTA:"
            strCol(1, 24) = VB6.Format(Arredondar(ldblQKwDifFatfp, 2), "#,##0.00")
            '
            strCol(1, 25) = "Kw ULT. TOTAL:"
            strCol(1, 26) = VB6.Format(Arredondar(ldblQKwFatUp, 2) + Arredondar(ldblQKwFatUfp, 2), "#,##0.00")
            strCol(1, 27) = "Kw ULT. PONTA:"
            strCol(1, 28) = VB6.Format(Arredondar(ldblQKwFatUp, 2), "#,##0.00")
            strCol(1, 29) = "Kw ULT. F.PONTA:"
            strCol(1, 30) = VB6.Format(Arredondar(ldblQKwFatUfp, 2), "#,##0.00")
            'Arlindo
            'strCol(1, 31) = "ENC. FATURADO:" 
            'strCol(1, 32) = Format(Arredondar(ldblQKwhFatpLiv, 2) + Arredondar(ldblQKwhFatfpLiv, 2) + Arredondar(ldblQKwhFatpBan, 2) + Arredondar(ldblQKwhFatiBan, 2) + Arredondar(ldblQKwhFatfpBan, 2) + Arredondar(ldblQKwhFatBan, 2), "#,##0.00")
            strCol(1, 31) = "ENC. FATURADO:"
            strCol(1, 32) = VB6.Format(Arredondar(ldblQKwhFatpLiv, 2) + Arredondar(ldblQKwhFatfpLiv, 2), "#,##0.00")
            strCol(1, 33) = "ENCARGO PONTA:"
            strCol(1, 34) = VB6.Format(Arredondar(ldblQKwhFatpLiv, 2), "#,##0.00")
            strCol(1, 35) = "ENCARGO F.PONTA:"
            strCol(1, 36) = VB6.Format(Arredondar(ldblQKwhFatfpLiv, 2), "#,##0.00")
            strCol(1, 37) = "RECEITA BAN TOTAL:"
            strCol(1, 38) = VB6.Format(Arredondar(ldblQKwhFatpBan, 2) + Arredondar(ldblQKwhFatiBan, 2) + Arredondar(ldblQKwhFatfpBan, 2) + Arredondar(ldblQKwhFatBan, 2), "#,##0.00")
            strCol(1, 39) = "RECEITA BAN P:"
            strCol(1, 40) = VB6.Format(Arredondar(ldblQKwhFatpBan, 2), "#,##0.00")
            strCol(1, 41) = "RECEITA BAN I:"
            strCol(1, 42) = VB6.Format(Arredondar(ldblQKwhFatiBan, 2), "#,##0.00")
            strCol(1, 43) = "RECEITA BAN FP:"
            strCol(1, 44) = VB6.Format(Arredondar(ldblQKwhFatfpBan, 2) + Arredondar(ldblQKwhFatBan, 2), "#,##0.00")
            strCol(1, 45) = "REVERSO TOTAL:"
            strCol(1, 46) = VB6.Format(Arredondar(ldblQKwhReversotot, 2), "#,##0.00")
            strCol(1, 47) = "REVERSO PONTA:"
            strCol(1, 48) = VB6.Format(Arredondar(ldblQKwhReversop, 2), "#,##0.00")
            strCol(1, 49) = "REVERSO INTER.:"
            strCol(1, 50) = VB6.Format(Arredondar(ldblQKwhReversoi, 2), "#,##0.00")
            strCol(1, 51) = "REVERSO F.PONTA:"
            strCol(1, 52) = VB6.Format(Arredondar(ldblQKwhReversofp, 2), "#,##0.00")
            strCol(1, 53) = "REV.SEFAZ TOTAL:"
            strCol(1, 54) = VB6.Format(Arredondar(ldblQKwhReversotot_sefaz, 2), "#,##0.00")
            strCol(1, 55) = "REV.SEFAZ PONTA:"
            strCol(1, 56) = VB6.Format(Arredondar(ldblQKwhReversop_sefaz, 2), "#,##0.00")
            strCol(1, 57) = "REV.SEFAZ INTER.:"
            strCol(1, 58) = VB6.Format(Arredondar(ldblQKwhReversoi_sefaz, 2), "#,##0.00")
            strCol(1, 59) = "REV.SEFAZ F.PONTA:"
            strCol(1, 60) = VB6.Format(Arredondar(ldblQKwhReversofp_sefaz, 2), "#,##0.00")

            'Grupo 2
            strCol(2, 1) = "CONS.REATIVO R$: "
            strCol(2, 2) = VB6.Format(Arredondar(ldblVConReatp, 3), "#,##0.00") 'VB6.Format(Arredondar(ldblVConReatp, 2) + Arredondar(ldblVConReatfp, 2) + Arredondar(ldblVDemReatp, 2) + Arredondar(ldblVDemReatfp, 2) + Arredondar(ldblVConReat, 2) + Arredondar(ldblVDemReat, 2), "#,##0.00")
            strCol(2, 3) = "R$:"
            strCol(2, 4) = VB6.Format(Arredondar(ldblVKwhFatp, 2) + Arredondar(ldblVKwhFati, 2) + Arredondar(ldblVKwhFatfp, 2) + Arredondar(ldblVKwhFat, 2) + (Arredondar(ldblVKwhDevp, 2) + Arredondar(ldblVKwhDevfp, 2)) + (Arredondar(ldblVKwhUtrp, 2) + Arredondar(ldblVKwhUtrfp, 2)), "#,##0.00") 'VB6.Format(Arredondar(ldblVKwhCons, 3), "#,##0.00")
            strCol(2, 5) = "R$:"
            strCol(2, 6) = VB6.Format(Arredondar(ldblVKwhFatp, 2) + Arredondar(ldblVKwhDevp, 2), "#,##0.00")
            strCol(2, 7) = "R$:"
            strCol(2, 8) = VB6.Format(Arredondar(ldblVKwhFati, 2), "#,##0.00")
            strCol(2, 9) = "R$:"
            strCol(2, 10) = VB6.Format(Arredondar(ldblVKwhFatfp, 2) + Arredondar(ldblVKwhFat, 2) + Arredondar(ldblVKwhDevfp, 2), "#,##0.00") 'VB6.Format(Arredondar(ldblVKwhFatfp, 3), "#,##0.00")
            strCol(2, 11) = "R$:"
            strCol(2, 12) = VB6.Format(Arredondar(ldblVKwFatp, 2) + Arredondar(ldblVKwFatfp, 2) + Arredondar(ldblVKwFat, 2) + ldblVConReatfp, "#,##0.00")
            strCol(2, 13) = "R$:"
            strCol(2, 14) = VB6.Format(Arredondar(ldblVConReatfp, 2), "#,##0.00")
            strCol(2, 15) = "R$:"
            strCol(2, 16) = VB6.Format(Arredondar(ldblVKwFatfp, 2) + Arredondar(ldblVKwFat, 2), "#,##0.00")

            ' Arlindo dif. demanda
            strCol(2, 17) = "R$:"
            strCol(2, 18) = VB6.Format(Arredondar(ldblVKwDifFatp, 2) + Arredondar(ldblVKwDifFatfp, 2), "#,##0.00")
            strCol(2, 19) = "R$:"
            strCol(2, 20) = VB6.Format(Arredondar(ldblVKwDifFatp, 2), "#,##0.00")
            strCol(2, 21) = "R$:"
            strCol(2, 22) = VB6.Format(Arredondar(ldblVKwDifFatfp, 2), "#,##0.00")
            '
            strCol(2, 23) = "R$:"
            strCol(2, 24) = VB6.Format(Arredondar(ldblVKwFatUp, 2) + Arredondar(ldblVKwFatUfp, 2), "#,##0.00")
            strCol(2, 25) = "R$:"
            strCol(2, 26) = VB6.Format(Arredondar(ldblVKwFatUp, 2), "#,##0.00")
            strCol(2, 27) = "R$:"
            strCol(2, 28) = VB6.Format(Arredondar(ldblVKwFatUfp, 2), "#,##0.00")
            'strCol(2, 27) = "R$:"
            'strCol(2, 28) = Format(Arredondar(ldblVKwhFatpLiv, 2) + Arredondar(ldblVKwhFatfpLiv, 2), "#,##0.00")
            'Arlindo
            'strCol(2, 29) = "R$:"
            'strCol(2, 30) = Format(Arredondar(ldblVKwhFatpLiv, 2) + Arredondar(ldblVKwhFatfpLiv, 2) + Arredondar(ldblVKwhFatp, 2) + Arredondar(ldblVKwhFati, 2) + Arredondar(ldblVKwhFatfp, 2) + Arredondar(ldblVKwhFat, 2) + (Arredondar(ldblVKwhDevp, 2) + Arredondar(ldblVKwhDevfp, 2)) + (Arredondar(ldblVKwhUtrp, 2) + Arredondar(ldblVKwhUtrfp, 2)), "#,##0.00")
            strCol(2, 29) = "R$:"
            strCol(2, 30) = VB6.Format(Arredondar(ldblVKwhFatpLiv, 2) + Arredondar(ldblVKwhFatfpLiv, 2), "#,##0.00")
            strCol(2, 31) = "R$:"
            strCol(2, 32) = VB6.Format(Arredondar(ldblVKwhFatpLiv, 2), "#,##0.00")
            strCol(2, 33) = "R$:"
            strCol(2, 34) = VB6.Format(Arredondar(ldblVKwhFatfpLiv, 2), "#,##0.00")
            strCol(2, 35) = "R$:"
            strCol(2, 36) = VB6.Format(Arredondar(ldblVKwhFatpBan, 2) + Arredondar(ldblVKwhFatiBan, 2) + Arredondar(ldblVKwhFatfpBan, 2) + Arredondar(ldblVKwhFatBan, 2), "#,##0.00")
            strCol(2, 37) = "R$:"
            strCol(2, 38) = VB6.Format(Arredondar(ldblVKwhFatpBan, 2), "#,##0.00")
            strCol(2, 39) = "R$:"
            strCol(2, 40) = VB6.Format(Arredondar(ldblVKwhFatiBan, 2), "#,##0.00")
            strCol(2, 41) = "R$:"
            strCol(2, 42) = VB6.Format(Arredondar(ldblVKwhFatfpBan, 2) + Arredondar(ldblVKwhFatBan, 2), "#,##0.00")
            strCol(2, 43) = "R$:"
            strCol(2, 44) = VB6.Format(Arredondar(-ldblVKwhReversotot, 2), "#,##0.00")
            strCol(2, 45) = "R$:"
            strCol(2, 46) = VB6.Format(Arredondar(-ldblVKwhReversop, 2), "#,##0.00")
            strCol(2, 47) = "R$:"
            strCol(2, 48) = VB6.Format(Arredondar(-ldblVKwhReversoi, 2), "#,##0.00")
            strCol(2, 49) = "R$:"
            strCol(2, 50) = VB6.Format(Arredondar(-ldblVKwhReversofp, 2), "#,##0.00")
            strCol(2, 51) = "R$:"
            strCol(2, 52) = VB6.Format(Arredondar(-ldblVKwhReversotot_sefaz, 2), "#,##0.00")
            strCol(2, 53) = "R$:"
            strCol(2, 54) = VB6.Format(Arredondar(-ldblVKwhReversop_sefaz, 2), "#,##0.00")
            strCol(2, 55) = "R$:"
            strCol(2, 56) = VB6.Format(Arredondar(-ldblVKwhReversoi_sefaz, 2), "#,##0.00")
            strCol(2, 57) = "R$:"
            strCol(2, 58) = VB6.Format(Arredondar(-ldblVKwhReversofp_sefaz, 2), "#,##0.00")

            'Grupo 3
            strCol(3, 1) = "CONVENIOS R$:"
            strCol(3, 2) = VB6.Format(Arredondar(ldblConvenios, 2), "#,##0.00")
            strCol(3, 3) = "DIVERSOS R$:"
            strCol(3, 4) = VB6.Format(Arredondar(ldblDiversos, 2), "#,##0.00")
            strCol(3, 5) = "TAXADOS R$:"
            strCol(3, 6) = VB6.Format(Arredondar(ldblTaxados, 2), "#,##0.00")
            strCol(3, 7) = "DEVOLUÇÃO R$:"
            strCol(3, 8) = VB6.Format(Arredondar(ldblDescontos, 2) * -1, "#,##0.00")
            strCol(3, 9) = "SUBSÍDIOS R$:"
            strCol(3, 10) = VB6.Format(Arredondar(ldblDescontos_1, 2) * -1, "#,##0.00")
            strCol(3, 11) = "CIP R$:"
            strCol(3, 12) = VB6.Format(Arredondar(ldblTip, 2), "#,##0.00")
            strCol(3, 13) = "ENC.FINANC. R$:"
            strCol(3, 14) = VB6.Format(Arredondar(ldblEncFinan, 2), "#,##0.00")
            strCol(3, 15) = "JUROS R$:"
            strCol(3, 16) = VB6.Format(Arredondar(ldblJuros, 2), "#,##0.00")
            strCol(3, 17) = "DIF.ELETR. R$:"
            strCol(3, 18) = VB6.Format(Arredondar(ldblDifEltrbr, 2), "#,##0.00")
            strCol(3, 19) = "ENCARGO R$:"
            strCol(3, 20) = VB6.Format(Arredondar(ldblEncargo, 2), "#,##0.00")
            strCol(3, 21) = "EUSD R$:"
            strCol(3, 22) = VB6.Format(Arredondar(ldblMust, 2), "#,##0.00")
            strCol(3, 23) = "kW DES.PROV. R$:"
            strCol(3, 24) = VB6.Format(Arredondar(ldblVkwDscProv, 2) * -1, "#,##0.00")
            strCol(3, 25) = "kW DES.REAL R$:"
            strCol(3, 26) = VB6.Format(Arredondar(ldblVkwDscReal, 2) * -1, "#,##0.00")
            strCol(3, 27) = "kW DEV.DIF. R$:"
            strCol(3, 28) = VB6.Format(Arredondar(ldblVkwDevCcee, 2) * -1, "#,##0.00")
            strCol(3, 29) = "kW COB.DIF. R$:"
            strCol(3, 30) = VB6.Format(Arredondar(ldblVkwCobCcee, 2), "#,##0.00")
            strCol(3, 31) = "kWh DES.PROV. R$:"
            strCol(3, 32) = VB6.Format(Arredondar(ldblVkwhDscProv, 2) * -1, "#,##0.00")
            strCol(3, 33) = "kWh DES.REAL R$:"
            strCol(3, 34) = VB6.Format(Arredondar(ldblVkwhDscReal, 2) * -1, "#,##0.00")
            strCol(3, 35) = "kWh DEV.DIF. R$:"
            strCol(3, 36) = VB6.Format(Arredondar(ldblVkwhDevCcee, 2) * -1, "#,##0.00")
            strCol(3, 37) = "kWh COB.DIF. R$:"
            strCol(3, 38) = VB6.Format(Arredondar(ldblVkwhCobCcee, 2), "#,##0.00")

            Dim ldblTotaisReversos As Double
            ldblTotaisReversos = Arredondar(ldblVKwhReversotot, 2) + Arredondar(ldblVKwhReversotot_sefaz, 2)

            ldblReceitaCompanhia = Arredondar(ldblVKwhFatp, 2) + Arredondar(ldblVKwhFati, 2) + Arredondar(ldblVKwhFatfp, 2) + Arredondar(ldblVKwhFatpBan, 2) + Arredondar(ldblVKwhFatiBan, 2) + Arredondar(ldblVKwhFatfpBan, 2) + Arredondar(ldblVKwhFatpLiv, 2) + Arredondar(ldblVKwhFatfpLiv, 2) + Arredondar(ldblVKwhDevp, 2) + Arredondar(ldblVKwhDevfp, 2) + Arredondar(ldblVKwhUtrp, 2) + Arredondar(ldblVKwhUtrfp, 2)
            ldblReceitaCompanhia = Arredondar(ldblReceitaCompanhia, 2) + Arredondar(ldblVKwhFat, 2) + Arredondar(ldblVKwhFatBan, 2) + Arredondar(ldblVKwFatp, 2) + Arredondar(ldblVKwFatfp, 2) + Arredondar(ldblVKwFat, 2) + Arredondar(ldblVKwDifFatp, 2) + Arredondar(ldblVKwDifFatfp, 2) + Arredondar(ldblVKwFatUp, 2) + Arredondar(ldblVKwFatUfp, 2)
            ldblReceitaCompanhia = Arredondar(ldblReceitaCompanhia, 2) + (Arredondar(ldblVConReatp, 2) + Arredondar(ldblVConReatfp, 2) + Arredondar(ldblVDemReatp, 2) + Arredondar(ldblVDemReatfp, 2) + Arredondar(ldblVConReat, 2) + Arredondar(ldblVDemReat, 2))

            ldblReceitaCompanhia = Arredondar(ldblReceitaCompanhia, 2) - Arredondar(ldblTotaisReversos, 2)

            'Fazer alguma coisa para o caso da CCEE da portaria para o valor do importe
            'If CLng(Right(Me.txtMesAno.Text, 4) & Left(Me.txtMesAno.Text, 2)) < glngPortaria_Sef_344_2019 Then
            '

            'ldblImporte = ldblVKwhFatp + ldblVKwhFati + ldblVKwhFatfp + ldblVKwhFatpBan + ldblVKwhFatiBan + ldblVKwhFatfpBan + ldblVKwhFatpLiv + ldblVKwhFatfpLiv + ldblVKwhDevp + ldblVKwhDevfp + ldblVKwhUtrp + ldblVKwhUtrfp
            'ldblImporte = ldblImporte + ldblVKwhFat + ldblVKwhFatBan + ldblVKwFatp + ldblVKwFatfp + ldblVKwFat + ldblVKwFatUp + ldblVKwFatUfp
            'ldblImporte = ldblImporte + (ldblVConReatp + ldblVConReatfp + ldblVDemReatp + ldblVDemReatfp + ldblVConReat + ldblVDemReat) + ldblIcms + ldblPis + ldblCofins
            'ldblImporte = ldblImporte - (ldblVkwDscProv + ldblVkwDscReal + ldblVkwDevCcee + ldblVkwhDscProv + ldblVkwhDscReal + ldblVkwhDevCcee) + ldblVkwCobCcee + ldblVkwhCobCcee + ldblVkwhReversoImporte

            'ldblImporte = Arredondar(ldblReceitaCompanhia, 2) + Arredondar(ldblIcms, 2) + Arredondar(ldblPis, 2) + Arredondar(ldblCofins, 2) + Arredondar(ldblIcmsSt, 2) + Arredondar(ldblPisSt, 2) + Arredondar(ldblCofinsSt, 2) - (Arredondar(ldblVkwDscProv, 2) + Arredondar(ldblVkwDscReal, 2) + Arredondar(ldblVkwDevCcee, 2) + Arredondar(ldblVkwhDscProv, 2) + Arredondar(ldblVkwhDscReal, 2) + Arredondar(ldblVkwhDevCcee, 2)) + Arredondar(ldblVkwCobCcee, 2) + Arredondar(ldblVkwhCobCcee, 2) - Arredondar(ldblDescontos_1, 2) + Arredondar(ldblVKwhReversotot, 2) + Arredondar(ldblVKwhReversotot_sefaz, 2)

            'ldblImporte = (Arredondar(ldblReceitaCompanhia, 2) + Arredondar(ldblIcms, 2) + Arredondar(ldblPis, 2) + Arredondar(ldblCofins, 2) + Arredondar(ldblIcmsSt, 2) + Arredondar(ldblPisSt, 2) + Arredondar(ldblCofinsSt, 2) - (Arredondar(ldblVkwDscProv, 2) + Arredondar(ldblVkwDscReal, 2) + Arredondar(ldblVkwDevCcee, 2) + Arredondar(ldblVkwhDscProv, 2) + Arredondar(ldblVkwhDscReal, 2) + Arredondar(ldblVkwhDevCcee, 2)) + Arredondar(ldblVkwCobCcee, 2) + Arredondar(ldblVkwhCobCcee, 2) - Arredondar(ldblDescontos_1, 2)) - Arredondar(ldblTotaisReversos, 2)
            ldblImporte = Arredondar(ldblReceitaCompanhia, 2) + Arredondar(ldblIcms, 2) + Arredondar(ldblPis, 2) + Arredondar(ldblCofins, 2) + Arredondar(ldblIcmsSt, 2) + Arredondar(ldblPisSt, 2) + Arredondar(ldblCofinsSt, 2) - (Arredondar(ldblVkwDscProv, 2) + Arredondar(ldblVkwDscReal, 2) + Arredondar(ldblVkwDevCcee, 2) + Arredondar(ldblVkwhDscProv, 2) + Arredondar(ldblVkwhDscReal, 2) + Arredondar(ldblVkwhDevCcee, 2)) + Arredondar(ldblVkwCobCcee, 2) + Arredondar(ldblVkwhCobCcee, 2) - Arredondar(ldblDescontos_1, 2)

            'ldblImporte = Arredondar(ldblReceitaCompanhia, 2) + Arredondar(ldblIcms, 2) + Arredondar(ldblPis, 2) + Arredondar(ldblCofins, 2) - (Arredondar(ldblVkwDscProv, 2) + Arredondar(ldblVkwDscReal, 2) + Arredondar(ldblVkwDevCcee, 2) + Arredondar(ldblVkwhDscProv, 2) + Arredondar(ldblVkwhDscReal, 2) + Arredondar(ldblVkwhDevCcee, 2)) + Arredondar(ldblVkwCobCcee, 2) + Arredondar(ldblVkwhCobCcee, 2) - Arredondar(ldblDescontos_1, 2)

            'ldblImporte = Arredondar(ldblIcms, 2) + Arredondar(ldblPis, 2) + Arredondar(ldblCofins, 2) + Arredondar(ldblIcmsSt, 2) + Arredondar(ldblPisSt, 2) + Arredondar(ldblCofinsSt, 2) - (Arredondar(ldblVkwDscProv, 2) + Arredondar(ldblVkwDscReal, 2) + Arredondar(ldblVkwDevCcee, 2) + Arredondar(ldblVkwhDscProv, 2) + Arredondar(ldblVkwhDscReal, 2) + Arredondar(ldblVkwhDevCcee, 2)) + Arredondar(ldblVkwCobCcee, 2) + Arredondar(ldblVkwhCobCcee, 2) - Arredondar(ldblDescontos_1, 2) + Arredondar(ldblVKwhReversotot, 2) + Arredondar(ldblVKwhReversotot_sefaz, 2)

            'Grupo 4
            strCol(4, 1) = "ICMS R$:"
            strCol(4, 2) = VB6.Format(Arredondar(ldblIcms, 2), "#,##0.00")
            strCol(4, 3) = "PIS R$:"
            strCol(4, 4) = VB6.Format(Arredondar(ldblPis, 2), "#,##0.00")
            strCol(4, 5) = "COFINS R$:"
            strCol(4, 6) = VB6.Format(Arredondar(ldblCofins, 2), "#,##0.00")
            strCol(4, 7) = "ICMS/PIS/COF R$:"
            strCol(4, 8) = VB6.Format(Arredondar(ldblIcms, 2) + Arredondar(ldblPis, 2) + Arredondar(ldblCofins, 2), "#,##0.00")
            strCol(4, 9) = "ICMS-ST R$:"
            strCol(4, 10) = VB6.Format(Arredondar(ldblIcmsSt, 2), "#,##0.00")
            strCol(4, 11) = "PIS-ST R$:"
            strCol(4, 12) = VB6.Format(Arredondar(ldblPisSt, 2), "#,##0.00")
            strCol(4, 13) = "COFINS-ST R$:"
            strCol(4, 14) = VB6.Format(Arredondar(ldblCofinsSt, 2), "#,##0.00")
            strCol(4, 15) = "TRIB.ST R$:"
            strCol(4, 16) = VB6.Format(Arredondar(ldblIcmsSt, 2) + Arredondar(ldblPisSt, 2) + Arredondar(ldblCofinsSt, 2), "#,##0.00")
            strCol(4, 17) = "REC.COMPANH. R$:"
            strCol(4, 18) = VB6.Format(Arredondar(ldblReceitaCompanhia, 2), "#,##0.00")
            strCol(4, 19) = "TOTAL 1102.1 R$:"
            strCol(4, 20) = VB6.Format(Arredondar(ldblImporte, 2), "#,##0.00")
            strCol(4, 21) = "TOTAL R$:"
            strCol(4, 22) = VB6.Format(Arredondar(ldblTotal, 2), "#,##0.00")
            strCol(4, 23) = "BASE ICMS R$:"
            strCol(4, 24) = VB6.Format(Arredondar(ldblBaseIcms, 2), "#,##0.00")
            strCol(4, 25) = "BASE PIS R$:"
            strCol(4, 26) = VB6.Format(Arredondar(ldblBasePis, 2), "#,##0.00")
            strCol(4, 27) = "BASE COFINS R$:"
            strCol(4, 28) = VB6.Format(Arredondar(ldblBaseCofins, 2), "#,##0.00")
            strCol(4, 29) = "DIFERIDO R$:"
            strCol(4, 30) = VB6.Format(Arredondar(ldblDiferido, 2), "#,##0.00")
            'strCol(4, 29) = "BASE TOTAL R$:" 
            'strCol(4, 30) = VB6.Format((Arredondar(ldblBaseIcms,2) + Arredondar(ldblDiferido,2)), "#,##0.00")
            strCol(4, 31) = "ISENTO R$:"
            strCol(4, 32) = VB6.Format(Arredondar(ldblIsentoIcms, 2), "#,##0.00")
            strCol(4, 33) = "RETENÇÃO R$:"
            strCol(4, 34) = VB6.Format(Arredondar(ldblRetencao, 2) * -1, "#,##0.00")


            vlist = repositorioEmpresa.Select(objEmpresa)

            If vlist.Count <> 0 Then

                For Each objEmpresaFor As entidadeEmpresa In vlist

                    bytBLOBData = objEmpresaFor.LOGOTIPO

                Next

            End If


            dt_Relatorio_1.Rows.Add(strCol(1, 1),
                                    strCol(1, 2),
                                    strCol(1, 3),
                                    strCol(1, 4),
                                    strCol(1, 5),
                                    strCol(1, 6),
                                    strCol(1, 7),
                                    strCol(1, 8),
                                    strCol(1, 9),
                                    strCol(1, 10),
                                    strCol(1, 11),
                                    strCol(1, 12),
                                    strCol(1, 13),
                                    strCol(1, 14),
                                    strCol(1, 15),
                                    strCol(1, 16),
                                    strCol(1, 17),
                                    strCol(1, 18),
                                    strCol(1, 19),
                                    strCol(1, 20),
                                    strCol(1, 21),
                                    strCol(1, 22),
                                    strCol(1, 23),
                                    strCol(1, 24),
                                    strCol(1, 25),
                                    strCol(1, 26),
                                    strCol(1, 27),
                                    strCol(1, 28),
                                    strCol(1, 29),
                                    strCol(1, 30),
                                    strCol(1, 31),
                                    strCol(1, 32),
                                    strCol(1, 33),
                                    strCol(1, 34),
                                    strCol(1, 35),
                                    strCol(1, 36),
                                    strCol(1, 37),
                                    strCol(1, 38),
                                    strCol(1, 39),
                                    strCol(1, 40),
                                    strCol(1, 41),
                                    strCol(1, 42),
                                    strCol(1, 43),
                                    strCol(1, 44),
                                    strCol(1, 45),
                                    strCol(1, 46),
                                    strCol(1, 47),
                                    strCol(1, 48),
                                    strCol(1, 49),
                                    strCol(1, 50),
                                    strCol(1, 51),
                                    strCol(1, 52),
                                    strCol(1, 53),
                                    strCol(1, 54),
                                    strCol(1, 55),
                                    strCol(1, 56),
                                    strCol(1, 57),
                                    strCol(1, 58),
                                    strCol(1, 59),
                                    strCol(1, 60),
                                    strCol(2, 1),
                                    strCol(2, 2),
                                    strCol(2, 3),
                                    strCol(2, 4),
                                    strCol(2, 5),
                                    strCol(2, 6),
                                    strCol(2, 7),
                                    strCol(2, 8),
                                    strCol(2, 9),
                                    strCol(2, 10),
                                    strCol(2, 11),
                                    strCol(2, 12),
                                    strCol(2, 13),
                                    strCol(2, 14),
                                    strCol(2, 15),
                                    strCol(2, 16),
                                    strCol(2, 17),
                                    strCol(2, 18),
                                    strCol(2, 19),
                                    strCol(2, 20),
                                    strCol(2, 21),
                                    strCol(2, 22),
                                    strCol(2, 23),
                                    strCol(2, 24),
                                    strCol(2, 25),
                                    strCol(2, 26),
                                    strCol(2, 27),
                                    strCol(2, 28),
                                    strCol(2, 29),
                                    strCol(2, 30),
                                    strCol(2, 31),
                                    strCol(2, 32),
                                    strCol(2, 33),
                                    strCol(2, 34),
                                    strCol(2, 35),
                                    strCol(2, 36),
                                    strCol(2, 37),
                                    strCol(2, 38),
                                    strCol(2, 39),
                                    strCol(2, 40),
                                    strCol(2, 41),
                                    strCol(2, 42),
                                    strCol(2, 43),
                                    strCol(2, 44),
                                    strCol(2, 45),
                                    strCol(2, 46),
                                    strCol(2, 47),
                                    strCol(2, 48),
                                    strCol(2, 49),
                                    strCol(2, 50),
                                    strCol(2, 51),
                                    strCol(2, 52),
                                    strCol(2, 53),
                                    strCol(2, 54),
                                    strCol(2, 55),
                                    strCol(2, 56),
                                    strCol(2, 57),
                                    strCol(2, 58),
                                    strCol(3, 1),
                                    strCol(3, 2),
                                    strCol(3, 3),
                                    strCol(3, 4),
                                    strCol(3, 5),
                                    strCol(3, 6),
                                    strCol(3, 7),
                                    strCol(3, 8),
                                    strCol(3, 9),
                                    strCol(3, 10),
                                    strCol(3, 11),
                                    strCol(3, 12),
                                    strCol(3, 13),
                                    strCol(3, 14),
                                    strCol(3, 15),
                                    strCol(3, 16),
                                    strCol(3, 17),
                                    strCol(3, 18),
                                    strCol(3, 19),
                                    strCol(3, 20),
                                    strCol(3, 21),
                                    strCol(3, 22),
                                    strCol(3, 23),
                                    strCol(3, 24),
                                    strCol(3, 25),
                                    strCol(3, 26),
                                    strCol(3, 27),
                                    strCol(3, 28),
                                    strCol(3, 29),
                                    strCol(3, 30),
                                    strCol(3, 31),
                                    strCol(3, 32),
                                    strCol(3, 33),
                                    strCol(3, 34),
                                    strCol(3, 35),
                                    strCol(3, 36),
                                    strCol(3, 37),
                                    strCol(3, 38),
                                    strCol(4, 1),
                                    strCol(4, 2),
                                    strCol(4, 3),
                                    strCol(4, 4),
                                    strCol(4, 5),
                                    strCol(4, 6),
                                    strCol(4, 7),
                                    strCol(4, 8),
                                    strCol(4, 9),
                                    strCol(4, 10),
                                    strCol(4, 11),
                                    strCol(4, 12),
                                    strCol(4, 13),
                                    strCol(4, 14),
                                    strCol(4, 15),
                                    strCol(4, 16),
                                    strCol(4, 17),
                                    strCol(4, 18),
                                    strCol(4, 19),
                                    strCol(4, 20),
                                    strCol(4, 21),
                                    strCol(4, 22),
                                    strCol(4, 23),
                                    strCol(4, 24),
                                    strCol(4, 25),
                                    strCol(4, 26),
                                    strCol(4, 27),
                                    strCol(4, 28),
                                    strCol(4, 29),
                                    strCol(4, 30),
                                    strCol(4, 31),
                                    strCol(4, 32),
                                    strCol(4, 33),
                                    strCol(4, 34),
                                    astrCabecTitulo,
                                    astrCabecGrupo,
                                    astrGrupo,
                                    tit,
                                    gstrEmpresa_Nome,
                                    gstrEmpresa_Endereco,
                                    gstrEmpresa_Fone + " - " + gstrEmpresa_Site,
                                    bytBLOBData)

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: Imprime" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Public Function CabecaRel(ByVal astrGrupo As String, Optional ByVal astrFase As String = "") As Object

        Dim strAux As String
        Dim strAux2 As String
        Dim sMontaData As String = cmbMesFim.Text & "/" & txtAno.Text
        Dim dData As Date

        dData = CDate(sMontaData)

        Try



            'If lstrOficial = "S" Then
            If Format(dData, "MM/yyyy") < CDate(istrMesAnoFat) Then
                If Me.chkPreviaFat.CheckState = System.Windows.Forms.CheckState.Checked Then
                    strAux = "OFICIAL - PRÉVIA DO FATURAMENTO " & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex)
                    If VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) <> VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex) Then
                        strAux = strAux & " até " & VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex)
                    End If
                    strAux = strAux & " de " & Me.txtAno.Text
                Else
                    If istrTabNf = "nf" Then
                        If chkRen863_2019.CheckState = System.Windows.Forms.CheckState.Unchecked Then
                            strAux = "OFICIAL - SIMPLES CONFERÊNCIA " & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex)
                        Else
                            strAux = "OFICIAL - Resumo do Faturamento Final " & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex)
                        End If
                        If VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) <> VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex) Then
                            strAux = strAux & " até " & VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex)
                        End If
                        strAux = strAux & " de " & Me.txtAno.Text
                    Else
                        If chkRen863_2019.CheckState = System.Windows.Forms.CheckState.Unchecked Then
                            strAux = "OFICIAL - SIMPLES CONFERÊNCIA " & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex)
                        Else
                            strAux = "OFICIAL - Conferência do Faturamento " & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex)
                        End If
                        If VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) <> VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex) Then
                            strAux = strAux & " até " & VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex)
                        End If
                        strAux = strAux & " de " & Me.txtAno.Text
                    End If
                End If
            Else
                If Me.chkPreviaFat.CheckState = System.Windows.Forms.CheckState.Checked Then
                    strAux = "NÃO OFICIAL - PRÉVIA DO FATURAMENTO " & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex)
                    If VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) <> VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex) Then
                        strAux = strAux & " até " & VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex)
                    End If
                    strAux = strAux & " de " & Me.txtAno.Text
                Else
                    If istrTabNf = "NF" Then
                        If chkRen863_2019.CheckState = System.Windows.Forms.CheckState.Unchecked Then
                            strAux = "NÃO OFICIAL - SIMPLES CONFERÊNCIA " & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex)
                        Else
                            strAux = "NÃO OFICIAL - Resumo do Faturamento Final " & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex)
                        End If
                        If VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) <> VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex) Then
                            strAux = strAux & " até " & VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex)
                        End If
                        strAux = strAux & " de " & Me.txtAno.Text
                    Else
                        If chkRen863_2019.CheckState = System.Windows.Forms.CheckState.Unchecked Then
                            strAux = "NÃO OFICIAL - SIMPLES CONFERÊNCIA " & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex)
                        Else
                            strAux = "NÃO OFICIAL - Conferência do Faturamento " & VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex)
                        End If
                        If VB6.GetItemString(Me.cmbMesIni, Me.cmbMesIni.SelectedIndex) <> VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex) Then
                            strAux = strAux & " até " & VB6.GetItemString(Me.cmbMesFim, Me.cmbMesFim.SelectedIndex)
                        End If
                        strAux = strAux & " de " & Me.txtAno.Text
                    End If
                End If
            End If

            strAux2 = "Grupo " & astrGrupo & " - Todas as Rotas "

            If CDbl(istrSocios) = 1 Then
                If Me.cmbSocios.SelectedIndex = 1 Then 'Somente socios
                    strAux2 = strAux2 & " (Somente Associados) "
                ElseIf Me.cmbSocios.SelectedIndex = 2 Then  'Não socios
                    strAux2 = strAux2 & " (Não Associados) "
                End If
            End If

            istrCabec_1 = strAux
            istrCabec_2 = strAux2


        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: CabecaRel" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Function
        End Try

    End Function

    Private Sub chkPlanilha_CheckedChanged(sender As Object, e As EventArgs) Handles chkPlanilha.CheckedChanged
        If chkPlanilha.Checked = True Then
            txtArq.Enabled = True
            cmdPasta.Enabled = True
        Else
            txtArq.Enabled = False
            cmdPasta.Enabled = false
        End If
    End Sub

    Private Sub ImprimeDetalhes(ByVal astrGrupo As String, Optional ByVal astrZona As String = "", Optional ByVal astrCabecTitulo As String = "", Optional ByVal astrCabecGrupo As String = "")

        Dim lstrTipo As String
        Dim ldblQtde As Double
        Dim ldblCanc As Double
        Dim ldblRefa As Double
        Dim ldblFatF As Double
        Dim ldblTotal As Double
        Dim strCodigo As String
        Dim lstrsql As String
        Dim ldblValor As Double

        Dim vlist

        Dim objTempEstatis As New entidadeTempEstatis
        Dim repositorioTempEstatis As New repositorioTempEstatis

        Try

            ldblTotal = 0
            ldblValor = 0
            ldblQtde = 0
            lstrTipo = ""
            strCodigo = ""



            ' DETALHAMENTO DOS DIVERSOS 
            lstrsql = ""
            lstrsql = lstrsql & "SELECT codigo, nome, SUM(valor) valor, grupo FROM " & istrTabTempItens & " WHERE "
            lstrsql = lstrsql & "MID(codigo,1,4) = 9080 AND codigo<>9080000098 GROUP BY codigo ORDER BY codigo ASC"

            objTempEstatis.TABLE = lstrsql
            dt = repositorioTempEstatis.Execute_2(objTempEstatis)

            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    'VB6.Format(Arredondar(ldblQKwDifFatp, 2), "#,##0.00")
                    strCodigo = IIf(IsDBNull(row.Item("codigo")), "", row.Item("codigo"))
                    ldblValor = IIf(IsDBNull(row.Item("valor")), 0, row.Item("valor"))
                    lstrTipo = IIf(IsDBNull(row.Item("nome")), "", row.Item("nome"))
                    'ldblQtde = 5 'IIf(IsDBNull(objTempEstatisFor.TARIFA_BRANCA), 0, objTempEstatisFor.TARIFA_BRANCA)

                    ldblTotal = ldblTotal + ldblValor


                    dt_Relatorio_2.Rows.Add("DETALHAMENTO DOS DIVERSOS", strCodigo, lstrTipo, VB6.Format(Arredondar(ldblValor, 2), "#,##0.00"), VB6.Format(Arredondar(ldblValor, 2), "#,##0.00"), astrCabecTitulo, astrCabecGrupo)

                Next
                dt_Relatorio_2.Rows.Add("DETALHAMENTO DOS DIVERSOS", "", "TOTAL", VB6.Format(Arredondar(ldblTotal, 2), "#,##0.00"), VB6.Format(Arredondar(ldblTotal, 2), "#,##0.00"), astrCabecTitulo, astrCabecGrupo)

            End If

            ldblTotal = 0

            ' DETALHAMENTO DOS TAXADOS
            lstrsql = ""
            lstrsql = lstrsql & "SELECT codigo, nome, SUM(valor) valor, grupo FROM " & istrTabTempItens & " WHERE "
            lstrsql = lstrsql & "MID(codigo,1,4) = 9040 GROUP BY codigo ORDER BY codigo ASC"

            objTempEstatis.TABLE = lstrsql
            dt = repositorioTempEstatis.Execute_2(objTempEstatis)

            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    strCodigo = IIf(IsDBNull(row.Item("codigo")), "", row.Item("codigo"))
                    ldblValor = IIf(IsDBNull(row.Item("valor")), 0, row.Item("valor"))
                    lstrTipo = IIf(IsDBNull(row.Item("nome")), "", row.Item("nome"))
                    'ldblQtde = 5 'IIf(IsDBNull(objTempEstatisFor.TARIFA_BRANCA), 0, objTempEstatisFor.TARIFA_BRANCA)

                    ldblTotal = ldblTotal + ldblValor

                    dt_Relatorio_2.Rows.Add("DETALHAMENTO DOS TAXADOS", strCodigo, lstrTipo, VB6.Format(Arredondar(ldblValor, 2), "#,##0.00"), VB6.Format(Arredondar(ldblValor, 2), "#,##0.00"), astrCabecTitulo, astrCabecGrupo)

                Next
                dt_Relatorio_2.Rows.Add("DETALHAMENTO DOS TAXADOS", "", "TOTAL", VB6.Format(Arredondar(ldblTotal, 2), "#,##0.00"), VB6.Format(Arredondar(ldblTotal, 2), "#,##0.00"), astrCabecTitulo, astrCabecGrupo)

            End If

            ldblTotal = 0

            ' DETALHAMENTO DOS CONVÊNIOS
            lstrsql = ""
            lstrsql = lstrsql & "SELECT codigo, nome, SUM(valor) valor, grupo FROM " & istrTabTempItens & " WHERE "
            lstrsql = lstrsql & "MID(codigo,1,4) = 9030 GROUP BY codigo ORDER BY codigo ASC"

            objTempEstatis.TABLE = lstrsql
            dt = repositorioTempEstatis.Execute_2(objTempEstatis)

            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    strCodigo = IIf(IsDBNull(row.Item("codigo")), "", row.Item("codigo"))
                    ldblValor = IIf(IsDBNull(row.Item("valor")), 0, row.Item("valor"))
                    lstrTipo = IIf(IsDBNull(row.Item("nome")), "", row.Item("nome"))
                    'ldblQtde = 5 'IIf(IsDBNull(objTempEstatisFor.TARIFA_BRANCA), 0, objTempEstatisFor.TARIFA_BRANCA)

                    ldblTotal = ldblTotal + ldblValor

                    dt_Relatorio_2.Rows.Add("DETALHAMENTO DOS CONVÊNIOS", strCodigo, lstrTipo, VB6.Format(Arredondar(ldblValor, 2), "#,##0.00"), VB6.Format(Arredondar(ldblValor, 2), "#,##0.00"), astrCabecTitulo, astrCabecGrupo)

                Next
                dt_Relatorio_2.Rows.Add("DETALHAMENTO DOS CONVÊNIOS", "", "TOTAL", VB6.Format(Arredondar(ldblTotal, 2), "#,##0.00"), VB6.Format(Arredondar(ldblTotal, 2), "#,##0.00"), astrCabecTitulo, astrCabecGrupo)

            End If

            ldblTotal = 0

            'DETALHAMENTO DAS RETENÇÕES
            lstrsql = ""
            lstrsql = lstrsql & "SELECT codigo, nome, SUM(valor) valor, grupo FROM " & istrTabTempItens & " WHERE "
            lstrsql = lstrsql & "(MID(codigo,1,4) = 9090 OR MID(codigo, 1, 10) = '9070000088') GROUP BY codigo ORDER BY codigo ASC"

            objTempEstatis.TABLE = lstrsql
            dt = repositorioTempEstatis.Execute_2(objTempEstatis)

            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    strCodigo = IIf(IsDBNull(row.Item("codigo")), "", row.Item("codigo"))
                    ldblValor = IIf(IsDBNull(row.Item("valor")), 0, row.Item("valor"))
                    lstrTipo = IIf(IsDBNull(row.Item("nome")), "", row.Item("nome"))
                    'ldblQtde = 5 'IIf(IsDBNull(objTempEstatisFor.TARIFA_BRANCA), 0, objTempEstatisFor.TARIFA_BRANCA)

                    ldblTotal = ldblTotal + ldblValor

                    dt_Relatorio_2.Rows.Add("DETALHAMENTO DAS RETENÇÕES", strCodigo, lstrTipo, VB6.Format(Arredondar(ldblValor, 2), "#,##0.00"), VB6.Format(Arredondar(ldblValor, 2), "#,##0.00"), astrCabecTitulo, astrCabecGrupo)

                Next
                dt_Relatorio_2.Rows.Add("DETALHAMENTO DAS RETENÇÕES", "", "TOTAL", VB6.Format(Arredondar(ldblTotal, 2), "#,##0.00"), VB6.Format(Arredondar(ldblTotal, 2), "#,##0.00"), astrCabecTitulo, astrCabecGrupo)

            End If

            ldblTotal = 0


            'DETALHAMENTO OUTROS(DIVERSOS)
            lstrsql = ""
            lstrsql = lstrsql & "SELECT codigo, nome, SUM(valor) valor, grupo FROM " & istrTabTempItens & " WHERE "
            lstrsql = lstrsql & "(MID(codigo,1,4) = 9070 AND MID(codigo, 1, 10) <> '9070000088'  OR codigo=9080000098 OR codigo=0302020032) GROUP BY codigo ORDER BY codigo ASC"

            objTempEstatis.TABLE = lstrsql
            dt = repositorioTempEstatis.Execute_2(objTempEstatis)

            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    strCodigo = IIf(IsDBNull(row.Item("codigo")), "", row.Item("codigo"))
                    ldblValor = IIf(IsDBNull(row.Item("valor")), 0, row.Item("valor"))
                    lstrTipo = IIf(IsDBNull(row.Item("nome")), "", row.Item("nome"))
                    'ldblQtde = 5 'IIf(IsDBNull(objTempEstatisFor.TARIFA_BRANCA), 0, objTempEstatisFor.TARIFA_BRANCA)

                    ldblTotal = ldblTotal + ldblValor

                    dt_Relatorio_2.Rows.Add("DETALHAMENTO OUTROS(DIVERSOS)", strCodigo, lstrTipo, VB6.Format(Arredondar(ldblValor, 2), "#,##0.00"), VB6.Format(Arredondar(ldblValor, 2), "#,##0.00"), astrCabecTitulo, astrCabecGrupo)

                Next
                dt_Relatorio_2.Rows.Add("DETALHAMENTO OUTROS(DIVERSOS)", "", "TOTAL", VB6.Format(Arredondar(ldblTotal, 2), "#,##0.00"), VB6.Format(Arredondar(ldblTotal, 2), "#,##0.00"), astrCabecTitulo, astrCabecGrupo)

            End If


            ldblTotal = 0

            'DETALHAMENTO DA ILUMINAÇÃO PÚBLICA
            'vFILTER = vFILTER + "  	      IF(TIP <> 0, 'NORMAL', 'ISENTO')  AS GRUPO, ";
            'vFILTER = vFILTER + "         COUNT(*)   AS TARIFA_BRANCA ";
            lstrsql = ""
            lstrsql = lstrsql & "SELECT IF(TIP <> 0, 'NORMAL', 'ISENTO')  AS GRUPO,  count(*) qtde FROM " & istrTabTemp & " group by 1 "
            'lstrsql = lstrsql & "(MID(codigo,1,4) = 9070 AND MID(codigo, 1, 10) <> '9070000088'  OR codigo=9080000098 OR codigo=0302020032) GROUP BY codigo ORDER BY codigo ASC"

            objTempEstatis.TABLE = lstrsql
            dt = repositorioTempEstatis.Execute_2(objTempEstatis)

            If dt.Rows.Count <> 0 Then

                For Each row As DataRow In dt.Rows

                    ' strCodigo = IIf(IsDBNull(row.Item("codigo")), "", row.Item("codigo"))
                    ldblValor = IIf(IsDBNull(row.Item("qtde")), 0, row.Item("qtde"))
                    lstrTipo = IIf(IsDBNull(row.Item("GRUPO")), "", row.Item("GRUPO"))
                    'ldblQtde = 5 'IIf(IsDBNull(objTempEstatisFor.TARIFA_BRANCA), 0, objTempEstatisFor.TARIFA_BRANCA)

                    ldblTotal = ldblTotal + ldblValor

                    dt_Relatorio_2.Rows.Add("DETALHAMENTO DA ILUMINAÇÃO PÚBLICA", "", lstrTipo, VB6.Format(Arredondar(ldblValor, 2), "#,##0.00"), VB6.Format(Arredondar(ldblValor, 2), "#,##0.00"), astrCabecTitulo, astrCabecGrupo)

                Next
                dt_Relatorio_2.Rows.Add("DETALHAMENTO DA ILUMINAÇÃO PÚBLICA", "", "TOTAL", VB6.Format(Arredondar(ldblTotal, 2), "#,##0.00"), VB6.Format(Arredondar(ldblTotal, 2), "#,##0.00"), astrCabecTitulo, astrCabecGrupo)

            End If


            'Fatura final, Faturas Canceladas, Refaturamento

            objTempEstatis.TABLE = istrTabTemp

            vlist = repositorioTempEstatis.Select_2(objTempEstatis)

            If vlist.Count > 0 Then

                For Each objTempEstatisFor As entidadeTempEstatis In vlist
                    ldblCanc = IIf(IsDBNull(objTempEstatisFor.FLGST), 0, Convert.ToDouble(IIf(objTempEstatisFor.FLGST = "", 0, objTempEstatisFor.FLGST)))
                    ldblRefa = IIf(IsDBNull(objTempEstatisFor.FLGMEDFAT), 0, Convert.ToDouble(IIf(objTempEstatisFor.FLGMEDFAT = "", 0, objTempEstatisFor.FLGMEDFAT)))
                    ldblFatF = IIf(IsDBNull(objTempEstatisFor.FATURA_FINAL), 0, Convert.ToDouble(IIf(objTempEstatisFor.FATURA_FINAL = 0, 0, objTempEstatisFor.FATURA_FINAL)))
                Next

                If (ldblCanc + ldblRefa + ldblFatF) > 0 Then

                    dt_Relatorio_2.Rows.Add("Detalhamento de Faturas Extras", "", "Canceladas", ldblCanc, "", astrCabecTitulo, astrCabecGrupo)
                    dt_Relatorio_2.Rows.Add("Detalhamento de Faturas Extras", "", "Refaturamento", ldblRefa, "", astrCabecTitulo, astrCabecGrupo)
                    dt_Relatorio_2.Rows.Add("Detalhamento de Faturas Extras", "", "Fatura Final", ldblFatF, "", astrCabecTitulo, astrCabecGrupo)
                    dt_Relatorio_2.Rows.Add("Detalhamento de Faturas Extras", "", "TOTAL", FormatNumber(ldblCanc + ldblRefa + ldblFatF, 0), "", astrCabecTitulo, astrCabecGrupo)

                End If

            End If

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: ImprimeDetalhes" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub
    Private Sub chktodas_CheckedChanged(sender As Object, e As EventArgs) Handles chktodas.CheckedChanged
        Try
            'Dim Item As System.Windows.Forms.ListViewItem = LVRota.Items(EventArgs.Index)
            Dim intConta As Short
            'If Item.Text = "Todas as rotas" Then
            If chktodas.Checked = True Then
                For intConta = 0 To lsvDtLeit.Items.Count - 1
                    'If lsvDtLeit.Items.Item(intConta).SubItems.Item(4).Text <> "" Then
                    lsvDtLeit.Items.Item(intConta).Checked = True
                    'End If
                Next
            ElseIf chktodas.Checked = False Then
                For intConta = 0 To lsvDtLeit.Items.Count - 1
                    lsvDtLeit.Items.Item(intConta).Checked = False
                Next intConta
            End If
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: chktodas_CheckedChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub
    Private Sub chktodos_CheckedChanged(sender As Object, e As EventArgs) Handles chktodos.CheckedChanged
        Try
            'Dim Item As System.Windows.Forms.ListViewItem = LVRota.Items(EventArgs.Index)
            Dim intConta As Short
            'If Item.Text = "Todas as rotas" Then
            If chktodos.Checked = True Then
                For intConta = 0 To lvsCidades.Items.Count - 1
                    lvsCidades.Items.Item(intConta).Checked = True
                Next
            ElseIf chktodos.Checked = False Then
                For intConta = 0 To lvsCidades.Items.Count - 1
                    lvsCidades.Items.Item(intConta).Checked = False
                Next intConta
            End If
        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: chktodos_CheckedChanged" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try
    End Sub

    Private Sub sGeraPlan_(ByVal grupo_tarifario As String,
                           ByVal grupo As String,
                           ByVal codigo_classe As String,
                          ByVal classe_faturada As String,
                          ByVal descricao_classe As String,
                          ByVal zona As String,
                          ByVal livro As String,
                          ByVal conta As String,
                           ByVal matricula As String,
                          ByVal nome As String,
                           ByVal numero_fatura As Double,
                           ByVal mesano_fatura As String,
                          ByVal mesano_referencia As String,
                           ByVal anomes_fat As String,
                           ByVal data_emissao As Date,
                          ByVal data_apresentacao As Date,
                           ByVal data_vencimento As Date,
                           ByVal data_leitura_atual As Date,
                          ByVal data_leitura_anterior As Date,
                           ByVal valor_consumo_reativo As Double,
                           ByVal valor_demanda_reativo As Double,
                          ByVal valor_consumo_reativo_ponta As Double,
                           ByVal valor_consumo_reativo_fora_ponta As Double,
                           ByVal valor_demanda_reativo_ponta As Double,
                          ByVal valor_demanda_reativo_fora_ponta As Double,
                           ByVal kwh_faturado As Double,
                           ByVal vlr_kwh_faturado As Double,
                          ByVal kwh_faturado_ponta As Double,
                           ByVal valor_kwh_faturado_ponta As Double,
                           ByVal kwh_faturado_fora_ponta As Double,
                          ByVal valor_kwh_faturado_fora_ponta As Double,
                           ByVal kwh_devolvido_ponta As Double,
                           ByVal valor_kwh_devolvido_ponta As Double,
                          ByVal kwh_devolvido_fora_ponta As Double,
                           ByVal valor_kwh_devolvido_fora_ponta As Double,
                           ByVal kwh_ultrapassado_ponta As Double,
                          ByVal valor_kwh_ultrapassado_ponta As Double,
                           ByVal kwh_ultrapassado_fora_ponta As Double,
                           ByVal valor_kwh_ultrapassado_fora_ponta As Double,
                          ByVal kw_faturado As Double,
                           ByVal valor_kw_faturado As Double,
                           ByVal kw_faturado_ponta As Double,
                          ByVal valor_kw_faturado_ponta As Double,
                           ByVal kw_faturado_fora_ponta As Double,
                           ByVal valor_kw_faturado_fora_ponta As Double,
                          ByVal kw_ultrapassado As Double,
                           ByVal valor_kw_ultrapassado As Double,
                           ByVal kw_ultrapassagem_ponta As Double,
                          ByVal valor_kw_ultrapassagem_ponta As Double,
                           ByVal kw_ultrapassado_fora_ponta As Double,
                           ByVal valor_kw_ultrapassado_fora_ponta As Double,
                          ByVal valor_desconto_provisorio As Double,
                           ByVal valor_desconto_realizado As Double,
                           ByVal valor_devolucao_diferenca_ccee As Double,
                          ByVal valor_cobranca_diferenca_ccee As Double,
                           ByVal valor_convenios As Double,
                           ByVal valor_diversos As Double,
                          ByVal valor_taxados As Double,
                           ByVal valor_devolucao As Double,
                           ByVal valor_encargos_financeiros As Double,
                          ByVal valor_retencao As Double,
                           ByVal valor_cip As Double,
                           ByVal valor_juros_ece As Double,
                          ByVal valor_diferenca_ece As Double,
                           ByVal valor_ece As Double,
                           ByVal valor_must As Double,
                          ByVal valor_icms As Double,
                           ByVal valor_pis As Double,
                           ByVal valor_cofins As Double,
                          ByVal valor_total As Double,
                           ByVal valor_liquido As Double,
                           ByVal demanda_contratada_convencional As Double,
                          ByVal demanda_contratada_ponta As Double,
                           ByVal demanda_contratada_fora_ponta As Double,
                           ByVal qtde_fx1 As Double,
                          ByVal qtde_fx2 As Double,
                           ByVal qtde_fx3 As Double,
                           ByVal qtde_fx4 As Double,
                          ByVal vlr_fx1 As Double,
                           ByVal vlr_fx2 As Double,
                           ByVal vlr_fx3 As Double,
                          ByVal vlr_fx4 As Double,
                           ByVal kwh_lido As Double,
                           ByVal fase As String,
                          ByVal base_icms_1 As Double,
                           ByVal aliquota_icms_1 As Double,
                           ByVal valor_icms_1 As Double,
                           ByVal base_icms_2 As Double,
                          ByVal aliquota_icms_2 As Double,
                           ByVal valor_icms_2 As Double,
                           ByVal base_pis As Double,
                          ByVal Aliquota_PIS As Double,
                           ByVal base_cofins As Double,
                           ByVal Aliquota_COFINS As Double,
                          ByVal receitas_financeiras As Double,
                           ByVal ressarcimento_idqual As Double,
                           ByVal valor_encargo_uso_sis_trans As Double,
                          ByVal desconto_must As Double,
                           ByVal encargo_kwh_faturado_ponta As Double,
                           ByVal encargo_valor_kwh_faturado_ponta As Double,
                          ByVal encargo_kwh_faturado_fora_ponta As Double,
                           ByVal encargo_valor_kwh_faturado_fora_ponta As Double,
                           ByVal mwh_medio As Double,
                          ByVal mwh_medio_horas As Double,
                           ByVal micro_geracao As Double,
                           ByVal VALOR_REVERSO As Double,
                          ByVal VALOR_REVERSO_BAN As Double,
                           ByVal REVERSO_PONTA As Double,
                           ByVal REVERSO_PONTA_BANDEIRA As Double,
                          ByVal REVERSO_FORA_DE_PONTA As Double,
                           ByVal REVERSO_FORA_DE_PONTA_BANDEIRA As Double,
                           ByVal bandeira_vlr_kwh_fat As Double,
                          ByVal bandeira_valor_kwh_fat_ponta As Double,
                           ByVal bandeira_valor_kwh_fat_fora_ponta As Double,
                           ByVal valor_energia_desconto_provisorio As Double,
                          ByVal valor_energia_desconto_realizado As Double,
                           ByVal valor_energia_devolucao_diferenca_ccee As Double,
                           ByVal valor_energia_cobranca_diferenca_ccee As Double,
                          ByVal CONSUMO_PONTA As Double,
                           ByVal CONSUMO_FORA_PONTA As Double,
                           ByVal REVERSO_FORA_PONTA As Double,
                          ByVal REVERSO_RESIDUO_FORA_PONTA As Double,
                           ByVal TUSD As Double,
                           ByVal CONSUMO_MEDIDO As Double,
                          ByVal REVERSO_LIDO As Double,
                           ByVal flgst As String,
                           ByVal datast As Date,
                           ByVal data_pagamento As Date,
                           ByVal kwh_faturado_Intermediaria As Double)
        Dim Linha As Integer

        Dim dt_1 As New DataTable
        Dim dtcab As New DataTable
        Dim dtCont As New DataTable
        Dim lblnAux As Boolean
        Dim lstrTab As String
        Dim llngIni As Integer
        Dim llngFim As Integer
        Dim llngAux As Integer
        Dim lstrSql As String

        'Dim misValue As Object = System.Reflection.Missing.Value
        Dim squalplanilha As String
        Dim inttotalReg As Integer

        Dim scabecalho As String
        Dim strlinha As String

        Try

            Dim Linhasql As Integer
            Dim sRetCodigos As String
            Dim sArrecadacaotexto As String
            Dim sHistoricotexto As String
            Dim dtotalGeral, dTotaldositens, dtotalDifer As Double
            Dim sTotalGeral As Object
            Dim iContador As Integer
            Dim iMaxLinha As Integer
            Dim dtTotal As DataTable
            Dim idBancoItem As Integer
            Dim dDataItem As String
            Dim dDataConsulta As String

            Dim vOpcao As String

            LinhaPlan = LinhaPlan + 1
            ExcelPlanilha.Cells(LinhaPlan, 1).value = grupo_tarifario 'grupo_tarifario
            ExcelPlanilha.Cells(LinhaPlan, 2).value = grupo
            ExcelPlanilha.Cells(LinhaPlan, 3).value = codigo_classe
            ExcelPlanilha.Cells(LinhaPlan, 4).value = classe_faturada
            ExcelPlanilha.Cells(LinhaPlan, 5).value = descricao_classe
            ExcelPlanilha.Cells(LinhaPlan, 6).value = zona
            ExcelPlanilha.Cells(LinhaPlan, 7).value = livro
            ExcelPlanilha.Cells(LinhaPlan, 8).value = conta
            ExcelPlanilha.Cells(LinhaPlan, 9).value = matricula
            ExcelPlanilha.Cells(LinhaPlan, 10).value = nome
            ExcelPlanilha.Cells(LinhaPlan, 11).value = numero_fatura
            ExcelPlanilha.Cells(LinhaPlan, 12).value = mesano_fatura
            ExcelPlanilha.Cells(LinhaPlan, 13).value = mesano_referencia
            ExcelPlanilha.Cells(LinhaPlan, 14).value = anomes_fat
            ExcelPlanilha.Cells(LinhaPlan, 15).value = data_emissao
            ExcelPlanilha.Cells(LinhaPlan, 16).value = data_apresentacao
            ExcelPlanilha.Cells(LinhaPlan, 17).value = data_vencimento
            ExcelPlanilha.Cells(LinhaPlan, 18).value = data_leitura_atual
            ExcelPlanilha.Cells(LinhaPlan, 19).value = data_leitura_anterior
            ExcelPlanilha.Cells(LinhaPlan, 20).value = valor_consumo_reativo
            ExcelPlanilha.Cells(LinhaPlan, 21).value = valor_demanda_reativo
            ExcelPlanilha.Cells(LinhaPlan, 22).value = valor_consumo_reativo_ponta
            ExcelPlanilha.Cells(LinhaPlan, 23).value = valor_consumo_reativo_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 24).value = valor_demanda_reativo_ponta
            ExcelPlanilha.Cells(LinhaPlan, 25).value = valor_demanda_reativo_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 26).value = kwh_faturado
            ExcelPlanilha.Cells(LinhaPlan, 27).value = vlr_kwh_faturado
            ExcelPlanilha.Cells(LinhaPlan, 28).value = kwh_faturado_ponta
            ExcelPlanilha.Cells(LinhaPlan, 29).value = valor_kwh_faturado_ponta
            ExcelPlanilha.Cells(LinhaPlan, 30).value = kwh_faturado_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 31).value = valor_kwh_faturado_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 32).value = kwh_devolvido_ponta
            ExcelPlanilha.Cells(LinhaPlan, 33).value = valor_kwh_devolvido_ponta
            ExcelPlanilha.Cells(LinhaPlan, 34).value = kwh_devolvido_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 35).value = valor_kwh_devolvido_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 36).value = kwh_ultrapassado_ponta
            ExcelPlanilha.Cells(LinhaPlan, 37).value = valor_kwh_ultrapassado_ponta
            ExcelPlanilha.Cells(LinhaPlan, 38).value = kwh_ultrapassado_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 39).value = valor_kwh_ultrapassado_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 40).value = kw_faturado
            ExcelPlanilha.Cells(LinhaPlan, 41).value = valor_kw_faturado
            ExcelPlanilha.Cells(LinhaPlan, 42).value = kw_faturado_ponta
            ExcelPlanilha.Cells(LinhaPlan, 43).value = valor_kw_faturado_ponta
            ExcelPlanilha.Cells(LinhaPlan, 44).value = kw_faturado_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 45).value = valor_kw_faturado_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 46).value = kw_ultrapassado
            ExcelPlanilha.Cells(LinhaPlan, 47).value = valor_kw_ultrapassado
            ExcelPlanilha.Cells(LinhaPlan, 48).value = kw_ultrapassagem_ponta
            ExcelPlanilha.Cells(LinhaPlan, 49).value = valor_kw_ultrapassagem_ponta
            ExcelPlanilha.Cells(LinhaPlan, 50).value = kw_ultrapassado_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 51).value = valor_kw_ultrapassado_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 52).value = valor_desconto_provisorio
            ExcelPlanilha.Cells(LinhaPlan, 53).value = valor_desconto_realizado
            ExcelPlanilha.Cells(LinhaPlan, 54).value = valor_devolucao_diferenca_ccee
            ExcelPlanilha.Cells(LinhaPlan, 55).value = valor_cobranca_diferenca_ccee
            ExcelPlanilha.Cells(LinhaPlan, 56).value = valor_convenios
            ExcelPlanilha.Cells(LinhaPlan, 57).value = valor_diversos
            ExcelPlanilha.Cells(LinhaPlan, 58).value = valor_taxados
            ExcelPlanilha.Cells(LinhaPlan, 59).value = valor_devolucao
            ExcelPlanilha.Cells(LinhaPlan, 60).value = valor_encargos_financeiros
            ExcelPlanilha.Cells(LinhaPlan, 61).value = valor_retencao
            ExcelPlanilha.Cells(LinhaPlan, 62).value = valor_cip
            ExcelPlanilha.Cells(LinhaPlan, 63).value = valor_juros_ece
            ExcelPlanilha.Cells(LinhaPlan, 64).value = valor_diferenca_ece
            ExcelPlanilha.Cells(LinhaPlan, 65).value = valor_ece
            ExcelPlanilha.Cells(LinhaPlan, 66).value = valor_must
            ExcelPlanilha.Cells(LinhaPlan, 67).value = valor_icms
            ExcelPlanilha.Cells(LinhaPlan, 68).value = valor_pis
            ExcelPlanilha.Cells(LinhaPlan, 69).value = valor_cofins
            ExcelPlanilha.Cells(LinhaPlan, 70).value = valor_total
            ExcelPlanilha.Cells(LinhaPlan, 71).value = valor_liquido
            ExcelPlanilha.Cells(LinhaPlan, 72).value = demanda_contratada_convencional
            ExcelPlanilha.Cells(LinhaPlan, 73).value = demanda_contratada_ponta
            ExcelPlanilha.Cells(LinhaPlan, 74).value = demanda_contratada_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 75).value = qtde_fx1
            ExcelPlanilha.Cells(LinhaPlan, 76).value = qtde_fx2
            ExcelPlanilha.Cells(LinhaPlan, 77).value = qtde_fx3
            ExcelPlanilha.Cells(LinhaPlan, 78).value = qtde_fx4
            ExcelPlanilha.Cells(LinhaPlan, 79).value = vlr_fx1
            ExcelPlanilha.Cells(LinhaPlan, 80).value = vlr_fx2
            ExcelPlanilha.Cells(LinhaPlan, 81).value = vlr_fx3
            ExcelPlanilha.Cells(LinhaPlan, 82).value = vlr_fx4
            ExcelPlanilha.Cells(LinhaPlan, 83).value = kwh_lido
            ExcelPlanilha.Cells(LinhaPlan, 84).value = fase
            ExcelPlanilha.Cells(LinhaPlan, 85).value = base_icms_1
            ExcelPlanilha.Cells(LinhaPlan, 86).value = aliquota_icms_1
            ExcelPlanilha.Cells(LinhaPlan, 87).value = valor_icms_1
            ExcelPlanilha.Cells(LinhaPlan, 88).value = base_icms_2
            ExcelPlanilha.Cells(LinhaPlan, 89).value = aliquota_icms_2
            ExcelPlanilha.Cells(LinhaPlan, 90).value = valor_icms_2
            ExcelPlanilha.Cells(LinhaPlan, 91).value = base_pis
            ExcelPlanilha.Cells(LinhaPlan, 92).value = Aliquota_PIS
            ExcelPlanilha.Cells(LinhaPlan, 93).value = base_cofins
            ExcelPlanilha.Cells(LinhaPlan, 94).value = Aliquota_COFINS
            ExcelPlanilha.Cells(LinhaPlan, 95).value = receitas_financeiras
            ExcelPlanilha.Cells(LinhaPlan, 96).value = ressarcimento_idqual
            ExcelPlanilha.Cells(LinhaPlan, 97).value = valor_encargo_uso_sis_trans
            ExcelPlanilha.Cells(LinhaPlan, 98).value = desconto_must
            ExcelPlanilha.Cells(LinhaPlan, 99).value = encargo_kwh_faturado_ponta
            ExcelPlanilha.Cells(LinhaPlan, 100).value = encargo_valor_kwh_faturado_ponta
            ExcelPlanilha.Cells(LinhaPlan, 101).value = encargo_kwh_faturado_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 102).value = encargo_valor_kwh_faturado_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 103).value = mwh_medio
            ExcelPlanilha.Cells(LinhaPlan, 104).value = mwh_medio_horas
            ExcelPlanilha.Cells(LinhaPlan, 105).value = micro_geracao
            ExcelPlanilha.Cells(LinhaPlan, 106).value = VALOR_REVERSO
            ExcelPlanilha.Cells(LinhaPlan, 107).value = VALOR_REVERSO_BAN
            ExcelPlanilha.Cells(LinhaPlan, 108).value = REVERSO_PONTA
            ExcelPlanilha.Cells(LinhaPlan, 109).value = REVERSO_PONTA_BANDEIRA
            ExcelPlanilha.Cells(LinhaPlan, 110).value = REVERSO_FORA_DE_PONTA
            ExcelPlanilha.Cells(LinhaPlan, 111).value = REVERSO_FORA_DE_PONTA_BANDEIRA
            ExcelPlanilha.Cells(LinhaPlan, 112).value = bandeira_vlr_kwh_fat
            ExcelPlanilha.Cells(LinhaPlan, 113).value = bandeira_valor_kwh_fat_ponta
            ExcelPlanilha.Cells(LinhaPlan, 114).value = bandeira_valor_kwh_fat_fora_ponta
            ExcelPlanilha.Cells(LinhaPlan, 115).value = valor_energia_desconto_provisorio
            ExcelPlanilha.Cells(LinhaPlan, 116).value = valor_energia_desconto_realizado
            ExcelPlanilha.Cells(LinhaPlan, 117).value = valor_energia_devolucao_diferenca_ccee
            ExcelPlanilha.Cells(LinhaPlan, 118).value = valor_energia_cobranca_diferenca_ccee
            ExcelPlanilha.Cells(LinhaPlan, 119).value = CONSUMO_PONTA
            ExcelPlanilha.Cells(LinhaPlan, 120).value = CONSUMO_FORA_PONTA
            ExcelPlanilha.Cells(LinhaPlan, 121).value = REVERSO_FORA_PONTA
            ExcelPlanilha.Cells(LinhaPlan, 122).value = REVERSO_RESIDUO_FORA_PONTA
            ExcelPlanilha.Cells(LinhaPlan, 123).value = TUSD
            ExcelPlanilha.Cells(LinhaPlan, 124).value = CONSUMO_MEDIDO
            ExcelPlanilha.Cells(LinhaPlan, 125).value = REVERSO_LIDO
            ExcelPlanilha.Cells(LinhaPlan, 126).value = flgst
            ExcelPlanilha.Cells(LinhaPlan, 127).value = datast
            ExcelPlanilha.Cells(LinhaPlan, 128).value = data_pagamento
            ExcelPlanilha.Cells(LinhaPlan, 129).value = REVERSO_FORA_DE_PONTA
            ExcelPlanilha.Cells(LinhaPlan, 130).value = 0 'IIf(IsDBNull(row("kwh_faturado_Ponta")), 0, row("kwh_faturado_Ponta")) '"kwh_faturado_Ponta"
            ExcelPlanilha.Cells(LinhaPlan, 131).value = 0 'IIf(IsDBNull(row("kwh_faturado_Intermediaria")), 0, row("kwh_faturado_Intermediaria")) '"kwh_faturado_Intermediaria"
            ExcelPlanilha.Cells(LinhaPlan, 132).value = 0 'IIf(IsDBNull(row("kwh_faturado_Fora_Ponta")), 0, row("kwh_faturado_Fora_Ponta")) '"kwh_faturado_Fora_Ponta"
            ExcelPlanilha.Cells(LinhaPlan, 133).value = 0 'IIf(IsDBNull(row("valor_dif_dem_contr")), 0, row("valor_dif_dem_contr")) '"valor_dif_dem_contr"
            ExcelPlanilha.Cells(LinhaPlan, 134).value = 0 'IIf(IsDBNull(row("banco")), 0, row("banco")) '"Leitura Anterior"
            ExcelPlanilha.Cells(LinhaPlan, 135).value = 0 'IIf(IsDBNull(row("banco")), 0, row("banco")) '"Leitura Atual"

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: sGeraPlan" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub
    Private Sub NomeArquivo()
        Dim lstrAux As String
        Dim sExtesion As String

        Try

            Me.txtArq.Text = My.Application.Info.DirectoryPath & "\" & istrNmArq & "." & Me.dialArqOpen.DefaultExt
            '  Me.dtpMesAno.CustomFormat = IIf(Me.opbAnual.Checked, "yyyy", "MM/yyyy")
            sExtesion = "xlsx"

            istrNmArq = "Fechamento_" & gstrEmpresa_Sigla & "_" & Format(Now, "ddmmyyyyhhmmss")

            lstrAux = StrReverse(Me.txtArq.Text)
            Me.txtArq.Text = StrReverse(Mid(lstrAux, CInt(InStr(lstrAux, "\")))) & istrNmArq & "." & sExtesion 'Me.dialArqOpen.DefaultExt
            System.Windows.Forms.Application.DoEvents()

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: NomeArquivo" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub sGeraPlan()

        Dim dt_1 As New DataTable
        Dim dtcab As New DataTable
        Dim dtCont As New DataTable
        Dim lblnAux As Boolean
        Dim lstrTab As String
        Dim llngIni As Integer
        Dim llngFim As Integer
        Dim llngAux As Integer
        Dim lstrSql As String

        Dim dt As New DataTable

        Dim objTempRecbtos As New entidadeTempRecbtos
        Dim repositorioTempRecbtos As New repositorioTempRecbtos

        Dim objTempRecbtosItensContabilidade As New entidadeTempRecbtosItensContabilidade
        Dim repositorioTempRecbtosItensContabilidade As New repositorioTempRecbtosItensContabilidade

        'Dim misValue As Object = System.Reflection.Missing.Value
        Dim squalplanilha As String
        Dim inttotalReg As Integer

        Dim scabecalho As String
        Dim strlinha As String

        Try

            'llngIni = LBound(istrNomClass)
            'llngFim = UBound(istrNomClass)

            Dim Linha As Integer = 1

            ' Monta o cabeçalho  
            ExcelPlanilha.Cells(Linha, 1).value = "grupo_tarifario"
            ExcelPlanilha.Cells(Linha, 2).value = "grupo"
            ExcelPlanilha.Cells(Linha, 3).value = "codigo_classe"
            ExcelPlanilha.Cells(Linha, 4).value = "classe_faturada"
            ExcelPlanilha.Cells(Linha, 5).value = "descricao_classe"
            ExcelPlanilha.Cells(Linha, 6).value = "zona"
            ExcelPlanilha.Cells(Linha, 7).value = "livro"
            ExcelPlanilha.Cells(Linha, 8).value = "conta"
            ExcelPlanilha.Cells(Linha, 9).value = "matricula"
            ExcelPlanilha.Cells(Linha, 10).value = "nome"
            ExcelPlanilha.Cells(Linha, 11).value = "numero_fatura"
            ExcelPlanilha.Cells(Linha, 12).value = "mesano_fatura"
            ExcelPlanilha.Cells(Linha, 13).value = "mesano_referencia"
            ExcelPlanilha.Cells(Linha, 14).value = "anomes_fat"
            ExcelPlanilha.Cells(Linha, 15).value = "data_emissao"
            ExcelPlanilha.Cells(Linha, 16).value = "data_apresentacao"
            ExcelPlanilha.Cells(Linha, 17).value = "data_vencimento"
            ExcelPlanilha.Cells(Linha, 18).value = "data_leitura_atual"
            ExcelPlanilha.Cells(Linha, 19).value = "data_leitura_anterior"
            ExcelPlanilha.Cells(Linha, 20).value = "valor_consumo_reativo"
            ExcelPlanilha.Cells(Linha, 21).value = "valor_demanda_reativo"
            ExcelPlanilha.Cells(Linha, 22).value = "valor_consumo_reativo_ponta"
            ExcelPlanilha.Cells(Linha, 23).value = "valor_consumo_reativo_fora_ponta"
            ExcelPlanilha.Cells(Linha, 24).value = "valor_demanda_reativo_ponta"
            ExcelPlanilha.Cells(Linha, 25).value = "valor_demanda_reativo_fora_ponta"
            ExcelPlanilha.Cells(Linha, 26).value = "kwh_faturado"
            ExcelPlanilha.Cells(Linha, 27).value = "vlr_kwh_faturado"
            ExcelPlanilha.Cells(Linha, 28).value = "kwh_faturado_ponta"
            ExcelPlanilha.Cells(Linha, 29).value = "valor_kwh_faturado_ponta"
            ExcelPlanilha.Cells(Linha, 30).value = "kwh_faturado_fora_ponta"
            ExcelPlanilha.Cells(Linha, 31).value = "valor_kwh_faturado_fora_ponta"
            ExcelPlanilha.Cells(Linha, 32).value = "kwh_devolvido_ponta"
            ExcelPlanilha.Cells(Linha, 33).value = "valor_kwh_devolvido_ponta"
            ExcelPlanilha.Cells(Linha, 34).value = "kwh_devolvido_fora_ponta"
            ExcelPlanilha.Cells(Linha, 35).value = "valor_kwh_devolvido_fora_ponta"
            ExcelPlanilha.Cells(Linha, 36).value = "kwh_ultrapassado_ponta"
            ExcelPlanilha.Cells(Linha, 37).value = "valor_kwh_ultrapassado_ponta"
            ExcelPlanilha.Cells(Linha, 38).value = "kwh_ultrapassado_fora_ponta"
            ExcelPlanilha.Cells(Linha, 39).value = "valor_kwh_ultrapassado_fora_ponta"
            ExcelPlanilha.Cells(Linha, 40).value = "kw_faturado"
            ExcelPlanilha.Cells(Linha, 41).value = "valor_kw_faturado"
            ExcelPlanilha.Cells(Linha, 42).value = "kw_faturado_ponta"
            ExcelPlanilha.Cells(Linha, 43).value = "valor_kw_faturado_ponta"
            ExcelPlanilha.Cells(Linha, 44).value = "kw_faturado_fora_ponta"
            ExcelPlanilha.Cells(Linha, 45).value = "valor_kw_faturado_fora_ponta"
            ExcelPlanilha.Cells(Linha, 46).value = "kw_ultrapassado"
            ExcelPlanilha.Cells(Linha, 47).value = "valor_kw_ultrapassado"
            ExcelPlanilha.Cells(Linha, 48).value = "kw_ultrapassagem_ponta"
            ExcelPlanilha.Cells(Linha, 49).value = "valor_kw_ultrapassagem_ponta"
            ExcelPlanilha.Cells(Linha, 50).value = "kw_ultrapassado_fora_ponta"
            ExcelPlanilha.Cells(Linha, 51).value = "valor_kw_ultrapassado_fora_ponta"
            ExcelPlanilha.Cells(Linha, 52).value = "valor_desconto_provisorio"
            ExcelPlanilha.Cells(Linha, 53).value = "valor_desconto_realizado"
            ExcelPlanilha.Cells(Linha, 54).value = "valor_devolucao_diferenca_ccee"
            ExcelPlanilha.Cells(Linha, 55).value = "valor_cobranca_diferenca_ccee"
            ExcelPlanilha.Cells(Linha, 56).value = "valor_convenios"
            ExcelPlanilha.Cells(Linha, 57).value = "valor_diversos"
            ExcelPlanilha.Cells(Linha, 58).value = "valor_taxados"
            ExcelPlanilha.Cells(Linha, 59).value = "valor_devolucao"
            ExcelPlanilha.Cells(Linha, 60).value = "valor_encargos_financeiros"
            ExcelPlanilha.Cells(Linha, 61).value = "valor_retencao"
            ExcelPlanilha.Cells(Linha, 62).value = "valor_cip"
            ExcelPlanilha.Cells(Linha, 63).value = "valor_juros_ece"
            ExcelPlanilha.Cells(Linha, 64).value = "valor_diferenca_ece"
            ExcelPlanilha.Cells(Linha, 65).value = "valor_ece"
            ExcelPlanilha.Cells(Linha, 66).value = "valor_must"
            ExcelPlanilha.Cells(Linha, 67).value = "valor_icms"
            ExcelPlanilha.Cells(Linha, 68).value = "valor_pis"
            ExcelPlanilha.Cells(Linha, 69).value = "valor_cofins"
            ExcelPlanilha.Cells(Linha, 70).value = "valor_total"
            ExcelPlanilha.Cells(Linha, 71).value = "valor_liquido"
            ExcelPlanilha.Cells(Linha, 72).value = "demanda_contratada_convencional"
            ExcelPlanilha.Cells(Linha, 73).value = "demanda_contratada_ponta"
            ExcelPlanilha.Cells(Linha, 74).value = "demanda_contratada_fora_ponta"
            ExcelPlanilha.Cells(Linha, 75).value = "qtde_fx1"
            ExcelPlanilha.Cells(Linha, 76).value = "qtde_fx2"
            ExcelPlanilha.Cells(Linha, 77).value = "qtde_fx3"
            ExcelPlanilha.Cells(Linha, 78).value = "qtde_fx4"
            ExcelPlanilha.Cells(Linha, 79).value = "vlr_fx1"
            ExcelPlanilha.Cells(Linha, 80).value = "vlr_fx2"
            ExcelPlanilha.Cells(Linha, 81).value = "vlr_fx3"
            ExcelPlanilha.Cells(Linha, 82).value = "vlr_fx4"
            ExcelPlanilha.Cells(Linha, 83).value = "kwh_lido"
            ExcelPlanilha.Cells(Linha, 84).value = "fase"
            ExcelPlanilha.Cells(Linha, 85).value = "base_icms_1"
            ExcelPlanilha.Cells(Linha, 86).value = "aliquota_icms_1"
            ExcelPlanilha.Cells(Linha, 87).value = "valor_icms_1"
            ExcelPlanilha.Cells(Linha, 88).value = "base_icms_2"
            ExcelPlanilha.Cells(Linha, 89).value = "aliquota_icms_2"
            ExcelPlanilha.Cells(Linha, 90).value = "valor_icms_2"
            ExcelPlanilha.Cells(Linha, 91).value = "base_pis"
            ExcelPlanilha.Cells(Linha, 92).value = "Aliquota_PIS()"
            ExcelPlanilha.Cells(Linha, 93).value = "base_cofins"
            ExcelPlanilha.Cells(Linha, 94).value = "Aliquota_COFINS()"
            ExcelPlanilha.Cells(Linha, 95).value = "receitas_financeiras"
            ExcelPlanilha.Cells(Linha, 96).value = "ressarcimento_idqual"
            ExcelPlanilha.Cells(Linha, 97).value = "valor_encargo_uso_sis_trans"
            ExcelPlanilha.Cells(Linha, 98).value = "desconto_must"
            ExcelPlanilha.Cells(Linha, 99).value = "encargo_kwh_faturado_ponta"
            ExcelPlanilha.Cells(Linha, 100).value = "encargo_valor_kwh_faturado_ponta"
            ExcelPlanilha.Cells(Linha, 101).value = "encargo_kwh_faturado_fora_ponta"
            ExcelPlanilha.Cells(Linha, 102).value = "encargo_valor_kwh_faturado_fora_ponta"
            ExcelPlanilha.Cells(Linha, 103).value = "mwh_medio"
            ExcelPlanilha.Cells(Linha, 104).value = "mwh_medio_horas"
            ExcelPlanilha.Cells(Linha, 105).value = "micro_geracao"
            ExcelPlanilha.Cells(Linha, 106).value = "VALOR REVERSO   "
            ExcelPlanilha.Cells(Linha, 107).value = "VALOR REVERSO BAN"
            ExcelPlanilha.Cells(Linha, 108).value = "REVERSO PONTA   "
            ExcelPlanilha.Cells(Linha, 109).value = "REVERSO PONTA BANDEIRA	"
            ExcelPlanilha.Cells(Linha, 110).value = "REVERSO FORA DE PONTA	"
            ExcelPlanilha.Cells(Linha, 111).value = "REVERSO FORA DE PONTA BANDEIRA"
            ExcelPlanilha.Cells(Linha, 112).value = "bandeira_vlr_kwh_fat"
            ExcelPlanilha.Cells(Linha, 113).value = "bandeira_valor_kwh_fat_ponta"
            ExcelPlanilha.Cells(Linha, 114).value = "bandeira_valor_kwh_fat_fora_ponta"
            ExcelPlanilha.Cells(Linha, 115).value = "valor_energia_desconto_provisorio"
            ExcelPlanilha.Cells(Linha, 116).value = "valor_energia_desconto_realizado"
            ExcelPlanilha.Cells(Linha, 117).value = "valor_energia_devolucao_diferenca_ccee"
            ExcelPlanilha.Cells(Linha, 118).value = "valor_energia_cobranca_diferenca_ccee"
            ExcelPlanilha.Cells(Linha, 119).value = "CONSUMO_PONTA"
            ExcelPlanilha.Cells(Linha, 120).value = "CONSUMO_FORA_PONTA"
            ExcelPlanilha.Cells(Linha, 121).value = "REVERSO_FORA_PONTA"
            ExcelPlanilha.Cells(Linha, 122).value = "REVERSO_RESIDUO_FORA_PONTA"
            ExcelPlanilha.Cells(Linha, 123).value = "TUSD"
            ExcelPlanilha.Cells(Linha, 124).value = "CONSUMO_MEDIDO"
            ExcelPlanilha.Cells(Linha, 125).value = "REVERSO_LIDO"
            ExcelPlanilha.Cells(Linha, 126).value = "flgst"
            ExcelPlanilha.Cells(Linha, 127).value = "datast"
            ExcelPlanilha.Cells(Linha, 128).value = "data_pagamento"
            ExcelPlanilha.Cells(Linha, 129).value = "REVERSO_FORA_DE_PONTA"
            ExcelPlanilha.Cells(Linha, 130).value = "kwh_faturado_Ponta"
            ExcelPlanilha.Cells(Linha, 131).value = "kwh_faturado_Intermediaria"
            ExcelPlanilha.Cells(Linha, 132).value = "kwh_faturado_Fora_Ponta"
            ExcelPlanilha.Cells(Linha, 133).value = "valor_dif_dem_contr"
            ExcelPlanilha.Cells(Linha, 134).value = "Leitura Anterior"
            ExcelPlanilha.Cells(Linha, 135).value = "Leitura Atual"


            Dim Linhasql As Integer
            Dim sRetCodigos As String
            Dim sArrecadacaotexto As String
            Dim sHistoricotexto As String
            Dim dtotalGeral, dTotaldositens, dtotalDifer As Double
            Dim sTotalGeral As Object
            Dim iContador As Integer
            Dim iMaxLinha As Integer
            Dim dtTotal As DataTable
            Dim idBancoItem As Integer
            Dim dDataItem As String
            Dim dDataConsulta As String

            ' Dim lstrsql As String
            Dim vOpcao As String

            'vOpcao = VB6.Format(adteFaixa, "dd/mm/yyyy")

            ' montagem do itens por Classe , Dia e Banco.
            'For llngAux = llngIni To llngFim - 2

            dtotalGeral = 0
            dTotaldositens = 0
            iMaxLinha = 0

            lstrSql = "SELECT *  FROM " & istrTabTemp & " Order by Nome, Zona, Livro, Conta asc " 'WHERE " & istrCondicao_Contabilidade(llngAux) & "  GROUP BY datapag, banco ORDER BY datapag ,banco "
            objTempRecbtosItensContabilidade.TABLE = lstrSql '
            dtCont = repositorioTempRecbtosItensContabilidade.Execute_2(objTempRecbtosItensContabilidade)

            If dtCont.Rows.Count > 0 Then

                Me.lblInfo.Text = "Populando a planilha com os dados...Aguarde !"
                BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 0, dtCont.Rows.Count)

                For Each row As DataRow In dtCont.Rows

                    Linha = Linha + 1
                    ExcelPlanilha.Cells(Linha, 1).value = IIf(IsDBNull(row("grupo_tarifario")), 0, row("grupo_tarifario")) 'grupo_tarifario
                    ExcelPlanilha.Cells(Linha, 2).value = IIf(IsDBNull(row("grupo")), 0, row("grupo")) '"grupo"
                    ExcelPlanilha.Cells(Linha, 3).value = IIf(IsDBNull(row("classe")), 0, row("classe")) '"codigo_classe"
                    ExcelPlanilha.Cells(Linha, 4).value = IIf(IsDBNull(row("classe_faturada")), "", row("classe_faturada")) '"classe_faturada"
                    ExcelPlanilha.Cells(Linha, 5).value = IIf(IsDBNull(row("descricao_classe")), "", row("descricao_classe")) '"descricao_classe"
                    ExcelPlanilha.Cells(Linha, 6).value = IIf(IsDBNull(row("zona")), 0, row("zona")) '"zona"
                    ExcelPlanilha.Cells(Linha, 7).value = IIf(IsDBNull(row("livro")), 0, row("livro")) '"livro"
                    ExcelPlanilha.Cells(Linha, 8).value = IIf(IsDBNull(row("conta")), 0, row("conta")) '"conta"
                    ExcelPlanilha.Cells(Linha, 9).value = IIf(IsDBNull(row("matricula")), 0, row("matricula")) '"matricula"
                    ExcelPlanilha.Cells(Linha, 10).value = IIf(IsDBNull(row("nome")), 0, row("nome")) '"nome"
                    ExcelPlanilha.Cells(Linha, 11).value = IIf(IsDBNull(row("numnf")), 0, row("numnf")) '"numero_fatura"
                    ExcelPlanilha.Cells(Linha, 12).value = IIf(IsDBNull(row("mesano")), "", row("mesano")) '"mesano_fatura"
                    ExcelPlanilha.Cells(Linha, 13).value = IIf(IsDBNull(row("mesano_referencia")), "", row("mesano_referencia")) '"mesano_referencia"
                    ExcelPlanilha.Cells(Linha, 14).value = IIf(IsDBNull(row("anomes_fat")), 0, row("anomes_fat")) '"anomes_fat"
                    ExcelPlanilha.Cells(Linha, 15).value = IIf(IsDBNull(row("data_emissao")), 0, row("data_emissao")) '"data_emissao"
                    ExcelPlanilha.Cells(Linha, 16).value = IIf(IsDBNull(row("data_apresentacao")), 0, row("data_apresentacao")) '"data_apresentacao"
                    ExcelPlanilha.Cells(Linha, 17).value = IIf(IsDBNull(row("data_vencimento")), 0, row("data_vencimento")) '"data_vencimento"
                    ExcelPlanilha.Cells(Linha, 18).value = IIf(IsDBNull(row("data_leitura_atual")), 0, row("data_leitura_atual")) '"data_leitura_atual"
                    ExcelPlanilha.Cells(Linha, 19).value = IIf(IsDBNull(row("data_leitura_anterior")), 0, row("data_leitura_anterior")) '"data_leitura_anterior"
                    ExcelPlanilha.Cells(Linha, 20).value = IIf(IsDBNull(row("VCONREAT")), 0, row("VCONREAT")) '"valor_consumo_reativo"
                    ExcelPlanilha.Cells(Linha, 21).value = IIf(IsDBNull(row("VDEMREAT")), 0, row("VDEMREAT")) '"valor_demanda_reativo"
                    ExcelPlanilha.Cells(Linha, 22).value = IIf(IsDBNull(row("VCONREAT_P")), 0, row("VCONREAT_P")) '"valor_consumo_reativo_ponta"
                    ExcelPlanilha.Cells(Linha, 23).value = IIf(IsDBNull(row("VCONREAT_FP")), 0, row("VCONREAT_FP")) '"valor_consumo_reativo_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 24).value = IIf(IsDBNull(row("VDEMREAT_P")), 0, row("VDEMREAT_P")) '"valor_demanda_reativo_ponta"
                    ExcelPlanilha.Cells(Linha, 25).value = IIf(IsDBNull(row("VDEMREAT_FP")), 0, row("VDEMREAT_FP")) '"valor_demanda_reativo_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 26).value = IIf(IsDBNull(row("QKWH_FAT")), 0, row("QKWH_FAT")) '"kwh_faturado"
                    ExcelPlanilha.Cells(Linha, 27).value = IIf(IsDBNull(row("VKWH_FAT")), 0, row("VKWH_FAT")) '"vlr_kwh_faturado"
                    ExcelPlanilha.Cells(Linha, 28).value = IIf(IsDBNull(row("QKWH_FAT_P")), 0, row("QKWH_FAT_P")) '"kwh_faturado_ponta"
                    ExcelPlanilha.Cells(Linha, 29).value = IIf(IsDBNull(row("VKWH_FAT_P")), 0, row("VKWH_FAT_P")) '"valor_kwh_faturado_ponta"
                    ExcelPlanilha.Cells(Linha, 30).value = IIf(IsDBNull(row("QKWH_FAT_FP")), 0, row("QKWH_FAT_FP")) '"kwh_faturado_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 31).value = IIf(IsDBNull(row("VKWH_FAT_FP")), 0, row("VKWH_FAT_FP")) '"valor_kwh_faturado_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 32).value = IIf(IsDBNull(row("QKWH_DEV_P")), 0, row("QKWH_DEV_P")) '"kwh_devolvido_ponta"
                    ExcelPlanilha.Cells(Linha, 33).value = IIf(IsDBNull(row("VKWH_DEV_P")), 0, row("VKWH_DEV_P")) '"valor_kwh_devolvido_ponta"
                    ExcelPlanilha.Cells(Linha, 34).value = IIf(IsDBNull(row("QKWH_DEV_FP")), 0, row("QKWH_DEV_FP")) '"kwh_devolvido_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 35).value = IIf(IsDBNull(row("VKWH_DEV_FP")), 0, row("VKWH_DEV_FP")) '"valor_kwh_devolvido_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 36).value = IIf(IsDBNull(row("QKWH_UTR_P")), 0, row("QKWH_UTR_P")) '"kwh_ultrapassado_ponta"
                    ExcelPlanilha.Cells(Linha, 37).value = IIf(IsDBNull(row("VKWH_UTR_P")), 0, row("VKWH_UTR_P")) '"valor_kwh_ultrapassado_ponta"
                    ExcelPlanilha.Cells(Linha, 38).value = IIf(IsDBNull(row("QKWH_UTR_FP")), 0, row("QKWH_UTR_FP")) '"kwh_ultrapassado_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 39).value = IIf(IsDBNull(row("VKWH_UTR_FP")), 0, row("VKWH_UTR_FP")) '"valor_kwh_ultrapassado_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 40).value = IIf(IsDBNull(row("QKW_FAT")), 0, row("QKW_FAT")) '"kw_faturado"
                    ExcelPlanilha.Cells(Linha, 41).value = IIf(IsDBNull(row("VKW_FAT")), 0, row("VKW_FAT")) '"valor_kw_faturado"
                    ExcelPlanilha.Cells(Linha, 42).value = IIf(IsDBNull(row("QKW_FAT_P")), 0, row("QKW_FAT_P")) '"kw_faturado_ponta"
                    ExcelPlanilha.Cells(Linha, 43).value = IIf(IsDBNull(row("VKW_FAT_P")), 0, row("VKW_FAT_P")) '"valor_kw_faturado_ponta"
                    ExcelPlanilha.Cells(Linha, 44).value = IIf(IsDBNull(row("QKW_FAT_FP")), 0, row("QKW_FAT_FP")) '"kw_faturado_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 45).value = IIf(IsDBNull(row("VKW_FAT_FP")), 0, row("VKW_FAT_FP")) '"valor_kw_faturado_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 46).value = IIf(IsDBNull(row("QKW_FATU_P")), 0, row("QKW_FATU_P")) '"kw_ultrapassado"
                    ExcelPlanilha.Cells(Linha, 47).value = IIf(IsDBNull(row("VKW_FATU_P")), 0, row("VKW_FATU_P")) '"valor_kw_ultrapassado"
                    ExcelPlanilha.Cells(Linha, 48).value = IIf(IsDBNull(row("QKW_FATU_P")), 0, row("QKW_FATU_P")) '"kw_ultrapassagem_ponta"
                    ExcelPlanilha.Cells(Linha, 49).value = IIf(IsDBNull(row("VKW_FATU_P")), 0, row("VKW_FATU_P")) '"valor_kw_ultrapassagem_ponta"
                    ExcelPlanilha.Cells(Linha, 50).value = IIf(IsDBNull(row("QKW_FATU_FP")), 0, row("QKW_FATU_FP")) '"kw_ultrapassado_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 51).value = IIf(IsDBNull(row("VKW_FATU_FP")), 0, row("VKW_FATU_FP")) '"valor_kw_ultrapassado_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 52).value = IIf(IsDBNull(row("VKW_DSC_PROV")), 0, row("VKW_DSC_PROV")) '"valor_desconto_provisorio"
                    ExcelPlanilha.Cells(Linha, 53).value = IIf(IsDBNull(row("VKW_DSC_REAL")), 0, row("VKW_DSC_REAL")) '"valor_desconto_realizado"
                    ExcelPlanilha.Cells(Linha, 54).value = IIf(IsDBNull(row("VKWH_DEV_CCEE")), 0, row("VKWH_DEV_CCEE")) '"valor_devolucao_diferenca_ccee"
                    ExcelPlanilha.Cells(Linha, 55).value = IIf(IsDBNull(row("VKWH_COB_CCEE")), 0, row("VKWH_COB_CCEE")) '"valor_cobranca_diferenca_ccee"
                    ExcelPlanilha.Cells(Linha, 56).value = IIf(IsDBNull(row("CONVENIOS")), 0, row("CONVENIOS")) '"valor_convenios"
                    ExcelPlanilha.Cells(Linha, 57).value = IIf(IsDBNull(row("DIVERSOS")), 0, row("DIVERSOS")) '"valor_diversos"
                    ExcelPlanilha.Cells(Linha, 58).value = IIf(IsDBNull(row("TAXADOS")), 0, row("TAXADOS")) '"valor_taxados"
                    ExcelPlanilha.Cells(Linha, 59).value = IIf(IsDBNull(row("DEVOLUCOES")), 0, row("DEVOLUCOES")) '"valor_devolucao"
                    ExcelPlanilha.Cells(Linha, 60).value = IIf(IsDBNull(row("ENC_FINAN")), 0, row("ENC_FINAN")) '"valor_encargos_financeiros"
                    ExcelPlanilha.Cells(Linha, 61).value = IIf(IsDBNull(row("RETENCAO")), 0, row("RETENCAO")) '"valor_retencao"
                    ExcelPlanilha.Cells(Linha, 62).value = IIf(IsDBNull(row("tip")), 0, row("tip")) '"valor_cip"
                    ExcelPlanilha.Cells(Linha, 63).value = IIf(IsDBNull(row("valor_juros_ece")), 0, row("valor_juros_ece")) '"valor_juros_ece"
                    ExcelPlanilha.Cells(Linha, 64).value = IIf(IsDBNull(row("valor_diferenca_ece")), 0, row("valor_diferenca_ece")) '"valor_diferenca_ece"
                    ExcelPlanilha.Cells(Linha, 65).value = IIf(IsDBNull(row("valor_ece")), 0, row("valor_ece")) '"valor_ece"
                    ExcelPlanilha.Cells(Linha, 66).value = IIf(IsDBNull(row("MUST")), 0, row("MUST")) '"valor_must"
                    ExcelPlanilha.Cells(Linha, 67).value = IIf(IsDBNull(row("icms")), 0, row("icms")) '"valor_icms"
                    ExcelPlanilha.Cells(Linha, 68).value = IIf(IsDBNull(row("pis")), 0, row("pis")) '"valor_pis"
                    ExcelPlanilha.Cells(Linha, 69).value = IIf(IsDBNull(row("cofins")), 0, row("cofins")) '"valor_cofins"
                    ExcelPlanilha.Cells(Linha, 70).value = IIf(IsDBNull(row("TOTAL")), 0, row("TOTAL")) '"valor_total"
                    ExcelPlanilha.Cells(Linha, 71).value = IIf(IsDBNull(row("valor_liquido")), 0, row("valor_liquido")) '"valor_liquido"
                    ExcelPlanilha.Cells(Linha, 72).value = IIf(IsDBNull(row("QKW_CONTR")), 0, row("QKW_CONTR")) '"demanda_contratada_convencional"
                    ExcelPlanilha.Cells(Linha, 73).value = IIf(IsDBNull(row("QKW_CONTR_P")), 0, row("QKW_CONTR_P")) '"demanda_contratada_ponta"
                    ExcelPlanilha.Cells(Linha, 74).value = IIf(IsDBNull(row("QKW_CONTR_FP")), 0, row("QKW_CONTR_FP")) '"demanda_contratada_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 75).value = IIf(IsDBNull(row("qtde_fx1")), 0, row("qtde_fx1")) '"qtde_fx1"
                    ExcelPlanilha.Cells(Linha, 76).value = IIf(IsDBNull(row("qtde_fx2")), 0, row("qtde_fx2")) '"qtde_fx2"
                    ExcelPlanilha.Cells(Linha, 77).value = IIf(IsDBNull(row("qtde_fx3")), 0, row("qtde_fx3")) '"qtde_fx3"
                    ExcelPlanilha.Cells(Linha, 78).value = IIf(IsDBNull(row("qtde_fx4")), 0, row("qtde_fx4")) '"qtde_fx4"
                    ExcelPlanilha.Cells(Linha, 79).value = IIf(IsDBNull(row("vlr_fx1")), 0, row("vlr_fx1")) '"vlr_fx1"
                    ExcelPlanilha.Cells(Linha, 80).value = IIf(IsDBNull(row("vlr_fx2")), 0, row("vlr_fx2")) '"vlr_fx2"
                    ExcelPlanilha.Cells(Linha, 81).value = IIf(IsDBNull(row("vlr_fx3")), 0, row("vlr_fx3")) '"vlr_fx3"
                    ExcelPlanilha.Cells(Linha, 82).value = IIf(IsDBNull(row("vlr_fx4")), 0, row("vlr_fx4")) '"vlr_fx4"
                    ExcelPlanilha.Cells(Linha, 83).value = IIf(IsDBNull(row("kwh_lido")), 0, row("kwh_lido")) '"kwh_lido"
                    ExcelPlanilha.Cells(Linha, 84).value = IIf(IsDBNull(row("FASE")), 0, row("FASE")) '"fase"
                    ExcelPlanilha.Cells(Linha, 85).value = IIf(IsDBNull(row("base_icms_1")), 0, row("base_icms_1")) '"base_icms_1"
                    ExcelPlanilha.Cells(Linha, 86).value = IIf(IsDBNull(row("aliquota_icms_1")), 0, row("aliquota_icms_1")) '"aliquota_icms_1"
                    ExcelPlanilha.Cells(Linha, 87).value = IIf(IsDBNull(row("valor_icms_1")), 0, row("valor_icms_1")) '"valor_icms_1"
                    ExcelPlanilha.Cells(Linha, 88).value = IIf(IsDBNull(row("base_icms_2")), 0, row("base_icms_2")) '"base_icms_2"
                    ExcelPlanilha.Cells(Linha, 89).value = IIf(IsDBNull(row("aliquota_icms_2")), 0, row("aliquota_icms_2")) '"aliquota_icms_2"
                    ExcelPlanilha.Cells(Linha, 90).value = IIf(IsDBNull(row("valor_icms_2")), 0, row("valor_icms_2")) '"valor_icms_2"
                    ExcelPlanilha.Cells(Linha, 91).value = IIf(IsDBNull(row("basepis")), 0, row("basepis")) '"base_pis"
                    ExcelPlanilha.Cells(Linha, 92).value = IIf(IsDBNull(row("Aliquota_PIS")), 0, row("Aliquota_PIS")) '"Aliquota_PIS"
                    ExcelPlanilha.Cells(Linha, 93).value = IIf(IsDBNull(row("basecofins")), 0, row("basecofins")) '"base_cofins"
                    ExcelPlanilha.Cells(Linha, 94).value = IIf(IsDBNull(row("Aliquota_COFINS")), 0, row("Aliquota_COFINS")) '"Aliquota_COFINS"
                    ExcelPlanilha.Cells(Linha, 95).value = IIf(IsDBNull(row("receitas_financeiras")), 0, row("receitas_financeiras")) '"receitas_financeiras"
                    ExcelPlanilha.Cells(Linha, 96).value = IIf(IsDBNull(row("ressarcimento_idqual")), 0, row("ressarcimento_idqual")) '"ressarcimento_idqual"
                    ExcelPlanilha.Cells(Linha, 97).value = IIf(IsDBNull(row("valor_encargo_uso_sis_trans")), 0, row("valor_encargo_uso_sis_trans")) '"valor_encargo_uso_sis_trans"
                    ExcelPlanilha.Cells(Linha, 98).value = IIf(IsDBNull(row("desconto_must")), 0, row("desconto_must")) '"desconto_must"
                    ExcelPlanilha.Cells(Linha, 99).value = IIf(IsDBNull(row("encargo_kwh_faturado_ponta")), 0, row("encargo_kwh_faturado_ponta")) '"encargo_kwh_faturado_ponta"
                    ExcelPlanilha.Cells(Linha, 100).value = IIf(IsDBNull(row("encargo_valor_kwh_faturado_ponta")), 0, row("encargo_valor_kwh_faturado_ponta")) '"encargo_valor_kwh_faturado_ponta"
                    ExcelPlanilha.Cells(Linha, 101).value = IIf(IsDBNull(row("encargo_kwh_faturado_fora_ponta")), 0, row("encargo_kwh_faturado_fora_ponta")) '"encargo_kwh_faturado_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 102).value = IIf(IsDBNull(row("encargo_valor_kwh_faturado_fora_ponta")), 0, row("encargo_valor_kwh_faturado_fora_ponta")) '"encargo_valor_kwh_faturado_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 103).value = IIf(IsDBNull(row("mwh_medio")), 0, row("mwh_medio")) '"mwh_medio"
                    ExcelPlanilha.Cells(Linha, 104).value = IIf(IsDBNull(row("mwh_medio_horas")), 0, row("mwh_medio_horas")) '"mwh_medio_horas"
                    ExcelPlanilha.Cells(Linha, 105).value = IIf(IsDBNull(row("micro_geracao")), 0, row("micro_geracao")) '"micro_geracao"
                    ExcelPlanilha.Cells(Linha, 106).value = IIf(IsDBNull(row("VALOR_REVERSO")), 0, row("VALOR_REVERSO")) '"VALOR REVERSO   "
                    ExcelPlanilha.Cells(Linha, 107).value = IIf(IsDBNull(row("VALOR_REVERSO_BAN")), 0, row("VALOR_REVERSO_BAN")) '"VALOR REVERSO BAN"
                    ExcelPlanilha.Cells(Linha, 108).value = IIf(IsDBNull(row("REVERSO_PONTA")), 0, row("REVERSO_PONTA")) '"REVERSO PONTA   "
                    ExcelPlanilha.Cells(Linha, 109).value = IIf(IsDBNull(row("REVERSO_PONTA_BANDEIRA")), 0, row("REVERSO_PONTA_BANDEIRA")) '"REVERSO PONTA BANDEIRA	"
                    ExcelPlanilha.Cells(Linha, 110).value = IIf(IsDBNull(row("REVERSO_FORA_DE_PONTA")), 0, row("REVERSO_FORA_DE_PONTA")) '"REVERSO FORA DE PONTA	"
                    ExcelPlanilha.Cells(Linha, 111).value = IIf(IsDBNull(row("REVERSO_FORA_DE_PONTA_BANDEIRA")), 0, row("REVERSO_FORA_DE_PONTA_BANDEIRA")) '"REVERSO FORA DE PONTA BANDEIRA"
                    ExcelPlanilha.Cells(Linha, 112).value = IIf(IsDBNull(row("bandeira_vlr_kwh_fat")), 0, row("bandeira_vlr_kwh_fat")) '"bandeira_vlr_kwh_fat"
                    ExcelPlanilha.Cells(Linha, 113).value = IIf(IsDBNull(row("bandeira_valor_kwh_fat_ponta")), 0, row("bandeira_valor_kwh_fat_ponta")) '"bandeira_valor_kwh_fat_ponta"
                    ExcelPlanilha.Cells(Linha, 114).value = IIf(IsDBNull(row("bandeira_valor_kwh_fat_fora_ponta")), 0, row("bandeira_valor_kwh_fat_fora_ponta")) '"bandeira_valor_kwh_fat_fora_ponta"
                    ExcelPlanilha.Cells(Linha, 115).value = IIf(IsDBNull(row("valor_energia_desconto_provisorio")), 0, row("valor_energia_desconto_provisorio")) '"valor_energia_desconto_provisorio"
                    ExcelPlanilha.Cells(Linha, 116).value = IIf(IsDBNull(row("valor_energia_desconto_realizado")), 0, row("valor_energia_desconto_realizado")) '"valor_energia_desconto_realizado"
                    ExcelPlanilha.Cells(Linha, 117).value = IIf(IsDBNull(row("valor_energia_devolucao_diferenca_ccee")), 0, row("valor_energia_devolucao_diferenca_ccee")) '"valor_energia_devolucao_diferenca_ccee"
                    ExcelPlanilha.Cells(Linha, 118).value = IIf(IsDBNull(row("valor_energia_cobranca_diferenca_ccee")), 0, row("valor_energia_cobranca_diferenca_ccee")) '"valor_energia_cobranca_diferenca_ccee"
                    ExcelPlanilha.Cells(Linha, 119).value = IIf(IsDBNull(row("CONSUMO_PONTA")), 0, row("CONSUMO_PONTA")) '"CONSUMO_PONTA"
                    ExcelPlanilha.Cells(Linha, 120).value = IIf(IsDBNull(row("CONSUMO_FORA_PONTA")), 0, row("CONSUMO_FORA_PONTA")) '"CONSUMO_FORA_PONTA"
                    ExcelPlanilha.Cells(Linha, 121).value = IIf(IsDBNull(row("REVERSO_FORA_PONTA")), 0, row("REVERSO_FORA_PONTA")) '"REVERSO_FORA_PONTA"
                    ExcelPlanilha.Cells(Linha, 122).value = IIf(IsDBNull(row("REVERSO_RESIDUO_FORA_PONTA")), 0, row("REVERSO_RESIDUO_FORA_PONTA")) '"REVERSO_RESIDUO_FORA_PONTA"
                    ExcelPlanilha.Cells(Linha, 123).value = IIf(IsDBNull(row("TUSD")), 0, row("TUSD")) '"TUSD"
                    ExcelPlanilha.Cells(Linha, 124).value = IIf(IsDBNull(row("CONSUMO_MEDIDO")), 0, row("CONSUMO_MEDIDO")) '"CONSUMO_MEDIDO"
                    ExcelPlanilha.Cells(Linha, 125).value = IIf(IsDBNull(row("REVERSO_LIDO")), 0, row("REVERSO_LIDO")) '"REVERSO_LIDO"
                    ExcelPlanilha.Cells(Linha, 126).value = IIf(IsDBNull(row("flgst")), 0, row("flgst")) '"flgst"
                    ExcelPlanilha.Cells(Linha, 127).value = IIf(IsDBNull(row("datast")), 0, row("datast")) '"datast"
                    ExcelPlanilha.Cells(Linha, 128).value = IIf(IsDBNull(row("data_pagamento")), 0, row("data_pagamento")) '"data_pagamento"
                    ExcelPlanilha.Cells(Linha, 129).value = IIf(IsDBNull(row("REVERSO_FORA_DE_PONTA")), 0, row("REVERSO_FORA_DE_PONTA")) '"REVERSO_FORA_DE_PONTA"
                    ExcelPlanilha.Cells(Linha, 130).value = 0 'IIf(IsDBNull(row("kwh_faturado_Ponta")), 0, row("kwh_faturado_Ponta")) '"kwh_faturado_Ponta"
                    ExcelPlanilha.Cells(Linha, 131).value = 0 'IIf(IsDBNull(row("kwh_faturado_Intermediaria")), 0, row("kwh_faturado_Intermediaria")) '"kwh_faturado_Intermediaria"
                    ExcelPlanilha.Cells(Linha, 132).value = 0 'IIf(IsDBNull(row("kwh_faturado_Fora_Ponta")), 0, row("kwh_faturado_Fora_Ponta")) '"kwh_faturado_Fora_Ponta"
                    ExcelPlanilha.Cells(Linha, 133).value = 0 'IIf(IsDBNull(row("valor_dif_dem_contr")), 0, row("valor_dif_dem_contr")) '"valor_dif_dem_contr"
                    ExcelPlanilha.Cells(Linha, 134).value = 0 'IIf(IsDBNull(row("banco")), 0, row("banco")) '"Leitura Anterior"
                    ExcelPlanilha.Cells(Linha, 135).value = 0 'IIf(IsDBNull(row("banco")), 0, row("banco")) '"Leitura Atual"

                    BarraProgresso(Me.ProgressBar, Me.lblPerc, Me.lblInfo, 1)
                Next
            End If
            'Next
            ' Next

        Catch ex As Exception
            MessageBox.Show("Ocorreu o Erro: " & Err.Description & " - Rotina: sGeraPlan" & "", "Aviso de Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

    End Sub

    Private Sub sCabecalhoPlan()

        Dim Linha As Integer = 1

        ' Monta o cabeçalho  
        ExcelPlanilha.Cells(Linha, 1).value = "grupo_tarifario"
        ExcelPlanilha.Cells(Linha, 2).value = "grupo"
        ExcelPlanilha.Cells(Linha, 3).value = "codigo_classe"
        ExcelPlanilha.Cells(Linha, 4).value = "classe_faturada"
        ExcelPlanilha.Cells(Linha, 5).value = "descricao_classe"
        ExcelPlanilha.Cells(Linha, 6).value = "zona"
        ExcelPlanilha.Cells(Linha, 7).value = "livro"
        ExcelPlanilha.Cells(Linha, 8).value = "conta"
        ExcelPlanilha.Cells(Linha, 9).value = "matricula"
        ExcelPlanilha.Cells(Linha, 10).value = "nome"
        ExcelPlanilha.Cells(Linha, 11).value = "numero_fatura"
        ExcelPlanilha.Cells(Linha, 12).value = "mesano_fatura"
        ExcelPlanilha.Cells(Linha, 13).value = "mesano_referencia"
        ExcelPlanilha.Cells(Linha, 14).value = "anomes_fat"
        ExcelPlanilha.Cells(Linha, 15).value = "data_emissao"
        ExcelPlanilha.Cells(Linha, 16).value = "data_apresentacao"
        ExcelPlanilha.Cells(Linha, 17).value = "data_vencimento"
        ExcelPlanilha.Cells(Linha, 18).value = "data_leitura_atual"
        ExcelPlanilha.Cells(Linha, 19).value = "data_leitura_anterior"
        ExcelPlanilha.Cells(Linha, 20).value = "valor_consumo_reativo"
        ExcelPlanilha.Cells(Linha, 21).value = "valor_demanda_reativo"
        ExcelPlanilha.Cells(Linha, 22).value = "valor_consumo_reativo_ponta"
        ExcelPlanilha.Cells(Linha, 23).value = "valor_consumo_reativo_fora_ponta"
        ExcelPlanilha.Cells(Linha, 24).value = "valor_demanda_reativo_ponta"
        ExcelPlanilha.Cells(Linha, 25).value = "valor_demanda_reativo_fora_ponta"
        ExcelPlanilha.Cells(Linha, 26).value = "kwh_faturado"
        ExcelPlanilha.Cells(Linha, 27).value = "vlr_kwh_faturado"
        ExcelPlanilha.Cells(Linha, 28).value = "kwh_faturado_ponta"
        ExcelPlanilha.Cells(Linha, 29).value = "valor_kwh_faturado_ponta"
        ExcelPlanilha.Cells(Linha, 30).value = "kwh_faturado_fora_ponta"
        ExcelPlanilha.Cells(Linha, 31).value = "valor_kwh_faturado_fora_ponta"
        ExcelPlanilha.Cells(Linha, 32).value = "kwh_devolvido_ponta"
        ExcelPlanilha.Cells(Linha, 33).value = "valor_kwh_devolvido_ponta"
        ExcelPlanilha.Cells(Linha, 34).value = "kwh_devolvido_fora_ponta"
        ExcelPlanilha.Cells(Linha, 35).value = "valor_kwh_devolvido_fora_ponta"
        ExcelPlanilha.Cells(Linha, 36).value = "kwh_ultrapassado_ponta"
        ExcelPlanilha.Cells(Linha, 37).value = "valor_kwh_ultrapassado_ponta"
        ExcelPlanilha.Cells(Linha, 38).value = "kwh_ultrapassado_fora_ponta"
        ExcelPlanilha.Cells(Linha, 39).value = "valor_kwh_ultrapassado_fora_ponta"
        ExcelPlanilha.Cells(Linha, 40).value = "kw_faturado"
        ExcelPlanilha.Cells(Linha, 41).value = "valor_kw_faturado"
        ExcelPlanilha.Cells(Linha, 42).value = "kw_faturado_ponta"
        ExcelPlanilha.Cells(Linha, 43).value = "valor_kw_faturado_ponta"
        ExcelPlanilha.Cells(Linha, 44).value = "kw_faturado_fora_ponta"
        ExcelPlanilha.Cells(Linha, 45).value = "valor_kw_faturado_fora_ponta"
        ExcelPlanilha.Cells(Linha, 46).value = "kw_ultrapassado"
        ExcelPlanilha.Cells(Linha, 47).value = "valor_kw_ultrapassado"
        ExcelPlanilha.Cells(Linha, 48).value = "kw_ultrapassagem_ponta"
        ExcelPlanilha.Cells(Linha, 49).value = "valor_kw_ultrapassagem_ponta"
        ExcelPlanilha.Cells(Linha, 50).value = "kw_ultrapassado_fora_ponta"
        ExcelPlanilha.Cells(Linha, 51).value = "valor_kw_ultrapassado_fora_ponta"
        ExcelPlanilha.Cells(Linha, 52).value = "valor_desconto_provisorio"
        ExcelPlanilha.Cells(Linha, 53).value = "valor_desconto_realizado"
        ExcelPlanilha.Cells(Linha, 54).value = "valor_devolucao_diferenca_ccee"
        ExcelPlanilha.Cells(Linha, 55).value = "valor_cobranca_diferenca_ccee"
        ExcelPlanilha.Cells(Linha, 56).value = "valor_convenios"
        ExcelPlanilha.Cells(Linha, 57).value = "valor_diversos"
        ExcelPlanilha.Cells(Linha, 58).value = "valor_taxados"
        ExcelPlanilha.Cells(Linha, 59).value = "valor_devolucao"
        ExcelPlanilha.Cells(Linha, 60).value = "valor_encargos_financeiros"
        ExcelPlanilha.Cells(Linha, 61).value = "valor_retencao"
        ExcelPlanilha.Cells(Linha, 62).value = "valor_cip"
        ExcelPlanilha.Cells(Linha, 63).value = "valor_juros_ece"
        ExcelPlanilha.Cells(Linha, 64).value = "valor_diferenca_ece"
        ExcelPlanilha.Cells(Linha, 65).value = "valor_ece"
        ExcelPlanilha.Cells(Linha, 66).value = "valor_must"
        ExcelPlanilha.Cells(Linha, 67).value = "valor_icms"
        ExcelPlanilha.Cells(Linha, 68).value = "valor_pis"
        ExcelPlanilha.Cells(Linha, 69).value = "valor_cofins"
        ExcelPlanilha.Cells(Linha, 70).value = "valor_total"
        ExcelPlanilha.Cells(Linha, 71).value = "valor_liquido"
        ExcelPlanilha.Cells(Linha, 72).value = "demanda_contratada_convencional"
        ExcelPlanilha.Cells(Linha, 73).value = "demanda_contratada_ponta"
        ExcelPlanilha.Cells(Linha, 74).value = "demanda_contratada_fora_ponta"
        ExcelPlanilha.Cells(Linha, 75).value = "qtde_fx1"
        ExcelPlanilha.Cells(Linha, 76).value = "qtde_fx2"
        ExcelPlanilha.Cells(Linha, 77).value = "qtde_fx3"
        ExcelPlanilha.Cells(Linha, 78).value = "qtde_fx4"
        ExcelPlanilha.Cells(Linha, 79).value = "vlr_fx1"
        ExcelPlanilha.Cells(Linha, 80).value = "vlr_fx2"
        ExcelPlanilha.Cells(Linha, 81).value = "vlr_fx3"
        ExcelPlanilha.Cells(Linha, 82).value = "vlr_fx4"
        ExcelPlanilha.Cells(Linha, 83).value = "kwh_lido"
        ExcelPlanilha.Cells(Linha, 84).value = "fase"
        ExcelPlanilha.Cells(Linha, 85).value = "base_icms_1"
        ExcelPlanilha.Cells(Linha, 86).value = "aliquota_icms_1"
        ExcelPlanilha.Cells(Linha, 87).value = "valor_icms_1"
        ExcelPlanilha.Cells(Linha, 88).value = "base_icms_2"
        ExcelPlanilha.Cells(Linha, 89).value = "aliquota_icms_2"
        ExcelPlanilha.Cells(Linha, 90).value = "valor_icms_2"
        ExcelPlanilha.Cells(Linha, 91).value = "base_pis"
        ExcelPlanilha.Cells(Linha, 92).value = "Aliquota_PIS()"
        ExcelPlanilha.Cells(Linha, 93).value = "base_cofins"
        ExcelPlanilha.Cells(Linha, 94).value = "Aliquota_COFINS()"
        ExcelPlanilha.Cells(Linha, 95).value = "receitas_financeiras"
        ExcelPlanilha.Cells(Linha, 96).value = "ressarcimento_idqual"
        ExcelPlanilha.Cells(Linha, 97).value = "valor_encargo_uso_sis_trans"
        ExcelPlanilha.Cells(Linha, 98).value = "desconto_must"
        ExcelPlanilha.Cells(Linha, 99).value = "encargo_kwh_faturado_ponta"
        ExcelPlanilha.Cells(Linha, 100).value = "encargo_valor_kwh_faturado_ponta"
        ExcelPlanilha.Cells(Linha, 101).value = "encargo_kwh_faturado_fora_ponta"
        ExcelPlanilha.Cells(Linha, 102).value = "encargo_valor_kwh_faturado_fora_ponta"
        ExcelPlanilha.Cells(Linha, 103).value = "mwh_medio"
        ExcelPlanilha.Cells(Linha, 104).value = "mwh_medio_horas"
        ExcelPlanilha.Cells(Linha, 105).value = "micro_geracao"
        ExcelPlanilha.Cells(Linha, 106).value = "VALOR REVERSO   "
        ExcelPlanilha.Cells(Linha, 107).value = "VALOR REVERSO BAN"
        ExcelPlanilha.Cells(Linha, 108).value = "REVERSO PONTA   "
        ExcelPlanilha.Cells(Linha, 109).value = "REVERSO PONTA BANDEIRA	"
        ExcelPlanilha.Cells(Linha, 110).value = "REVERSO FORA DE PONTA	"
        ExcelPlanilha.Cells(Linha, 111).value = "REVERSO FORA DE PONTA BANDEIRA"
        ExcelPlanilha.Cells(Linha, 112).value = "bandeira_vlr_kwh_fat"
        ExcelPlanilha.Cells(Linha, 113).value = "bandeira_valor_kwh_fat_ponta"
        ExcelPlanilha.Cells(Linha, 114).value = "bandeira_valor_kwh_fat_fora_ponta"
        ExcelPlanilha.Cells(Linha, 115).value = "valor_energia_desconto_provisorio"
        ExcelPlanilha.Cells(Linha, 116).value = "valor_energia_desconto_realizado"
        ExcelPlanilha.Cells(Linha, 117).value = "valor_energia_devolucao_diferenca_ccee"
        ExcelPlanilha.Cells(Linha, 118).value = "valor_energia_cobranca_diferenca_ccee"
        ExcelPlanilha.Cells(Linha, 119).value = "CONSUMO_PONTA"
        ExcelPlanilha.Cells(Linha, 120).value = "CONSUMO_FORA_PONTA"
        ExcelPlanilha.Cells(Linha, 121).value = "REVERSO_FORA_PONTA"
        ExcelPlanilha.Cells(Linha, 122).value = "REVERSO_RESIDUO_FORA_PONTA"
        ExcelPlanilha.Cells(Linha, 123).value = "TUSD"
        ExcelPlanilha.Cells(Linha, 124).value = "CONSUMO_MEDIDO"
        ExcelPlanilha.Cells(Linha, 125).value = "REVERSO_LIDO"
        ExcelPlanilha.Cells(Linha, 126).value = "flgst"
        ExcelPlanilha.Cells(Linha, 127).value = "datast"
        ExcelPlanilha.Cells(Linha, 128).value = "data_pagamento"
        ExcelPlanilha.Cells(Linha, 129).value = "REVERSO_FORA_DE_PONTA"
        ExcelPlanilha.Cells(Linha, 130).value = "kwh_faturado_Ponta"
        ExcelPlanilha.Cells(Linha, 131).value = "kwh_faturado_Intermediaria"
        ExcelPlanilha.Cells(Linha, 132).value = "kwh_faturado_Fora_Ponta"
        ExcelPlanilha.Cells(Linha, 133).value = "valor_dif_dem_contr"
        ExcelPlanilha.Cells(Linha, 134).value = "Leitura Anterior"
        ExcelPlanilha.Cells(Linha, 135).value = "Leitura Atual"

    End Sub



#End Region

End Class