Option Strict Off
Option Explicit On
Imports VB = Microsoft.VisualBasic
Module MDcomum
	Public Const LVM_FIRST As Integer = &H1000
	Public Const LVM_SETTEXTBKCOLOR As Integer = (LVM_FIRST + 38)
	
	Public Const NUMERICO As Short = 0
	Public Const ALFANUMERICO As Short = 1
	Public Const REAVISO As Short = 0
	Public Const CORTE As Short = 1
	Public Const SW_SHOWNORMAL As Integer = 1
	
	Public myConC As New ADODB.Connection
	Public myCmdC As New ADODB.Command
	Public gadoOraclCx As ADODB.Connection
	Public gadoOraclCm As ADODB.Command
	Public MyConCSite As New ADODB.Connection
	Public MyCmdCSite As New ADODB.Command
	
	Public Mmdc As New VB6.FixedLengthString(1)
	
	Public codserv As String
	Public VlrCodServ As String
	Public RefCodServ As String
	Public IndCodServ As Integer
	
	Public Declare Function GetComputerName Lib "kernel32"  Alias "GetComputerNameA"(ByVal lpBuffer As String, ByRef nSize As Integer) As Integer
	Public Declare Function SendMessage Lib "user32"  Alias "SendMessageA"(ByVal Hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
	Public Declare Function ShellExecute Lib "shell32.dll"  Alias "ShellExecuteA"(ByVal Hwnd As Integer, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Integer) As Integer
	Structure classeEtarifa
		'UPGRADE_WARNING: Fixed-length string size must fit in the buffer. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="3C1E4426-0B80-443E-B943-0627CD55D48B"'
		<VBFixedString(6),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,SizeConst:=6)> Public classe() As Char
		'UPGRADE_WARNING: Fixed-length string size must fit in the buffer. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="3C1E4426-0B80-443E-B943-0627CD55D48B"'
		<VBFixedString(6),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,SizeConst:=6)> Public ta() As Char
	End Structure
	
	Structure ClasseCons
		'UPGRADE_WARNING: Fixed-length string size must fit in the buffer. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="3C1E4426-0B80-443E-B943-0627CD55D48B"'
		<VBFixedString(6),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,SizeConst:=6)> Public classe() As Char
		Dim cons As Short
	End Structure
	
	'Usado para passar e receber valores de campos CheckBox
	Public Structure ptpeCadConsumidorCamposParametros
		Dim NomeCampo() As String
		Dim tipo() As String
		Dim valor() As Boolean
	End Structure
	
	'Usado para passar e recever valores de campos textbox
	Public Structure ptpeCadConsumidorCamposLeituras
		Dim NomeCampo() As String
		Dim tipo() As String
		Dim precisao() As Short
		Dim habilitado() As Boolean
		Dim valor() As String
	End Structure
	
	
	Public gstrErro(9000) As Object
	
	Public Function GetComputer() As String
		'Função para retornar o nome do computador que está logado no sistema
		Dim lstrBuffer As String
		Dim llngSize As Integer
		Dim llngDl As Integer
		Dim lstrRet As String
		On Error GoTo ErroGetComputer
		llngSize = 199
		lstrBuffer = New String(Chr(0), 200)
		llngDl = GetComputerName(lstrBuffer, llngSize)
		
		If llngDl <> 0 Then
			lstrRet = Left(lstrBuffer, llngSize)
			lstrRet = Replace(Replace(Replace(Replace(lstrRet, "-", ""), "/", ""), "_", ""), ".", "")
			lstrRet = LCase(RetiraAcentuacao(Trim(lstrRet)))
		Else
			lstrRet = ""
		End If
ErroGetComputer: 
		If Err.Number > 0 Then
			Call MsgBox("Erro: " & Err.Number & " - " & Err.Description, MsgBoxStyle.Information, gstrTituloMensagem)
		End If
		GetComputer = lstrRet
	End Function
	
	Public Function Conectar(ByVal astrSql As String, ByRef aRs As ADODB.Recordset, Optional ByVal ablnVerificaVersao As Boolean = True, Optional ByRef alblnGravaAuditoria As Boolean = False, Optional ByVal ablnRecordReadOnly As Boolean = False) As Boolean
		'Esta função é utilizada para buscar informações do banco MySQL
		'Ela usa o objeto que é defenido pela origem de chamada
		Dim lblnRetorno As Boolean
		lblnRetorno = True
		On Error GoTo ErroConectar
		If Len(Trim(astrSql)) > 0 Then
			With myCmdC
				.let_ActiveConnection(myConC)
				'adCmdTable usa-se para quando vier somente o nome da tabela sem a query
				'adCmdText usa-se para quando vier a query (Select * from ....
				'adCndStoredProc usa0se para quando precisar executar uma procedure ou função no banco de dados
				.CommandType = ADODB.CommandTypeEnum.adCmdText
				.CommandText = astrSql
			End With
			'Clipboard.Clear
			'Clipboard.SetText astrSql
			With aRs
				If ablnRecordReadOnly Then
					'adOpenForwardOnly Pode ser usado somente o MoveNext ou MovePrevious. Não pode ser usado o MoveFirst e nem o MoveLast
					'adOpenStatic Usa todos os Move... mas não poderá ver as alterações dos registros
					'adOpenKeyset Usa todos os Move... mas vê as alterações e exclusões
					'adOpenDynamic Usa todos os Move... mas vê as alterações, exclusões e inclusões.
					
					.CursorType = ADODB.CursorTypeEnum.adOpenForwardOnly
					'adLockReadOnly - Somente leitura Deixa mais rápido a consulta
					'adLockOptimistic - Pode incluir, alterar e excluir os registros.
					'adLockPessimistic -  Pode incluir, alterar e excluir os registros. Mas bloqueia o acesso a esta tabela para os outros usuários.
					.LockType = ADODB.LockTypeEnum.adLockReadOnly
					.CursorLocation = ADODB.CursorLocationEnum.adUseClient
				Else
					.CursorType = ADODB.CursorTypeEnum.adOpenKeyset
					.LockType = ADODB.LockTypeEnum.adLockOptimistic
					.CursorLocation = ADODB.CursorLocationEnum.adUseClient
				End If
				'.CacheSize = 1000
				.Open(myCmdC)
			End With
		End If
		If ablnVerificaVersao Then
			lblnRetorno = VerificaVersaoSistema
		End If
ErroConectar: 
		With myConC
			If .Errors.Count > 0 Then
				If .Errors.Item(.Errors.Count - 1).NativeError = 2006 Then
					Call MsgBox("Código: " & .Errors.Item(.Errors.Count - 1).NativeError & vbCrLf & "Descrição: " & .Errors.Item(.Errors.Count - 1).Description, MsgBoxStyle.Critical, gstrTituloMensagem)
					Call myConC.Close()
					Call Carrega_Banco()
					Resume Next
				End If
				lblnRetorno = False
				Call MsgBox("Código: " & .Errors.Item(.Errors.Count - 1).NativeError & vbCrLf & "Descrição: " & .Errors.Item(.Errors.Count - 1).Description, MsgBoxStyle.Critical, gstrTituloMensagem)
				If alblnGravaAuditoria Then
					Call Executar("INSERT INTO " & gstrDataBase & ".`auditoria_comandos_lc` (`movimento`,`comando`) VALUES('" & VB6.Format(BuscaHoraBD, "yyyy-MM-dd HH:NN:SS") & "','" & Replace(astrSql, "'", "\'") & "')")
				End If
			End If
		End With
		Conectar = lblnRetorno
		'Clipboard.Clear
		'Clipboard.SetText astrSql
	End Function
	
	Public Function ConectarSite(ByVal astrSql As String, ByRef aRs As ADODB.Recordset, Optional ByVal ablnVerificaVersao As Boolean = True, Optional ByRef astrRetErro As String = "") As Boolean
		Dim lblnRet As Boolean
		lblnRet = True
		On Error GoTo ErroConectarSite
		If Len(Trim(astrSql)) > 0 Then
			With MyCmdCSite
				.let_ActiveConnection(MyConCSite.ConnectionString)
				.CommandType = ADODB.CommandTypeEnum.adCmdText
				.CommandText = astrSql
				.CommandTimeout = 0
			End With
			With aRs
				Call .Open(MyCmdCSite, MyCmdCSite.ActiveConnection, ADODB.CursorTypeEnum.adOpenKeyset, ADODB.LockTypeEnum.adLockOptimistic)
			End With
		End If
ErroConectarSite: 
		With MyConCSite
			If .Errors.Count > 0 Then
				astrRetErro = "Código: " & .Errors.Item(.Errors.Count - 1).NativeError & " Descrição: " & .Errors.Item(.Errors.Count - 1).Description
				lblnRet = False
			End If
		End With
		ConectarSite = lblnRet
	End Function
	
	Public Function VerificaVersaoSistema() As Boolean
		Dim lblnRetorno As Boolean
		Dim lstrVersaoLocal As String
		Dim ldblVersaoLocal As Double
		Dim lstrVersaoBanco As String
		Dim ldblVersaoBanco As Double
		On Error GoTo ErroVerificaVersaoSistema
		lblnRetorno = True
		'UPGRADE_ISSUE: App property App.LogMode was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="076C26E5-B7A9-4E77-B69C-B4448DF39E58"'
		If LogMode = 1 Then '0 = modo de desenvolvimento 1 = modo compilado
			lstrVersaoLocal = VB6.Format(My.Application.Info.Version.Major, "0000") & VB6.Format(My.Application.Info.Version.Minor, "0000") & VB6.Format(My.Application.Info.Version.Revision, "0000")
			ldblVersaoLocal = CDbl(lstrVersaoLocal)
			lstrVersaoBanco = LeConfig("VERSAO_SISTEMA")
			If lstrVersaoBanco = "-1" Then
				Call CriaParConfig("VERSAO_SISTEMA", CStr(ldblVersaoLocal), False, "Versao do sistema")
				ldblVersaoBanco = ldblVersaoLocal
			ElseIf lstrVersaoBanco = "" Then 
				Call GravaConfig("VERSAO_SISTEMA", CStr(ldblVersaoLocal))
				ldblVersaoBanco = ldblVersaoLocal
			Else
				ldblVersaoBanco = CDbl(IIf(IsNumeric(lstrVersaoBanco), lstrVersaoBanco, 0))
			End If
			If ldblVersaoLocal > ldblVersaoBanco Then
				Call GravaConfig("VERSAO_SISTEMA", CStr(ldblVersaoLocal))
				ldblVersaoBanco = ldblVersaoLocal
			ElseIf ldblVersaoBanco <> ldblVersaoLocal Then 
				If frmNovoSplash.Visible = False Then
					Call MsgBox("A versão do sistema esta desatualizada! O sistema será finalizado. Favor atualizar o sistema.", MsgBoxStyle.Information, gstrTituloMensagem)
					lblnRetorno = False
					Call FechaTodosFormsAbertos()
					'        If FrmAtPrincipal.Visible = True Then
					'          Call Unload(FrmAtPrincipal)
					'        End If
				End If
			End If
		End If
ErroVerificaVersaoSistema: 
		If Err.Number > 0 Then
			lblnRetorno = False
			Call MsgBox("Erro: " & Err.Number & " - " & Err.Description, MsgBoxStyle.Information, gstrTituloMensagem)
		End If
		VerificaVersaoSistema = lblnRetorno
	End Function
	
	Private Sub FechaTodosFormsAbertos()
		Dim Form As Object
		For	Each Form In My.Application.OpenForms
			'UPGRADE_ISSUE: Unload Form was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="875EBAD7-D704-4539-9969-BC7DBDAA62A2"'
			Call Unload(Form)
			'UPGRADE_NOTE: Object Form may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
			Form = Nothing
		Next Form
	End Sub
	
	Public Function ConectarOrcl(ByVal astrSql As String, ByRef arstAuxiliar As ADODB.Recordset) As Boolean
		'Esta função é utilizada para buscar informações do banco MySQL
		'Ela usa o objeto que é defenido pela origem de chamada
		Dim lblnRetorno As Boolean
		lblnRetorno = True
		On Error GoTo ErroConectarOrcl
		If Len(Trim(astrSql)) > 0 Then
			With gadoOraclCm
				.let_ActiveConnection(gadoOraclCx)
				.CommandType = ADODB.CommandTypeEnum.adCmdText
				.CommandText = astrSql
			End With
			With arstAuxiliar
				.LockType = ADODB.LockTypeEnum.adLockBatchOptimistic 'adLockOptimistic
				.CursorType = ADODB.CursorTypeEnum.adOpenDynamic 'adOpenKeyset
				.CursorLocation = ADODB.CursorLocationEnum.adUseClient
				.Open(gadoOraclCm)
			End With
		End If
ErroConectarOrcl: 
		If Err.Number > 0 Then
			lblnRetorno = False
			Call MsgBox("Erro: " & Err.Number & " - " & Err.Description & " - " & Err.Source, MsgBoxStyle.Information, gstrTituloMensagem)
		End If
		ConectarOrcl = lblnRetorno
	End Function
	
	Public Function Executar(ByVal astrSql As String, Optional ByRef alblnGravaAuditoria As Boolean = False, Optional ByRef adblRowAfetados As Double = 0, Optional ByVal ablnStartTransaction As Boolean = True, Optional ByVal ablnTrataErro As Boolean = True) As Boolean
		On Error GoTo ErroExecutar
		Dim lblnRet As Boolean
		lblnRet = True
		'Clipboard.Clear
		'Clipboard.SetText astrSql
		With myConC
			'If ablnStartTransaction Then Call .Execute("START TRANSACTION")
			Call .Execute(astrSql, adblRowAfetados)
			'If ablnStartTransaction Then Call .Execute("COMMIT")
ErroExecutar: 
			If ablnTrataErro Then
				If .Errors.Count > 0 Then
					If .Errors.Item(.Errors.Count - 1).NativeError = 1451 Then
						Call MsgBox("Código: " & .Errors.Item(.Errors.Count - 1).NativeError & vbCrLf & "Descrição: " & "Não foi possível alterar ou deletar o registro pelo motivo de possuir vinculo com o cadastro de " & Mid(.Errors.Item(.Errors.Count - 1).Description, InStr(1, .Errors.Item(.Errors.Count - 1).Description, "`" & gstrDataBase & "`.`") + Len("`" & gstrDataBase & "`.`"), InStr(1, Mid(.Errors.Item(.Errors.Count - 1).Description, InStr(1, .Errors.Item(.Errors.Count - 1).Description, "`" & gstrDataBase & "`.`") + Len("`" & gstrDataBase & "`.`")), "`") - 1) & "!", MsgBoxStyle.Exclamation, gstrTituloMensagem)
					ElseIf .Errors.Item(.Errors.Count - 1).NativeError = 1062 Then 
						Call MsgBox("Código: " & .Errors.Item(.Errors.Count - 1).NativeError & vbCrLf & "Descrição: " & "Não foi possível incluir ou alterar o registro pois já foi informado em outro registro!", MsgBoxStyle.Critical, gstrTituloMensagem)
					Else
						Call MsgBox("Código: " & .Errors.Item(.Errors.Count - 1).NativeError & vbCrLf & "Descrição: " & .Errors.Item(.Errors.Count - 1).Description, MsgBoxStyle.Critical, gstrTituloMensagem)
					End If
					lblnRet = False
					'If ablnStartTransaction Then Call .Execute("ROLLBACK")
				End If
			End If
		End With
		If Not lblnRet Then
			If alblnGravaAuditoria Then
				Call Executar("INSERT INTO " & gstrDataBase & ".`auditoria_comandos_lc` (`movimento`,`comando`) VALUES('" & VB6.Format(BuscaHoraBD, "yyyy-MM-dd HH:NN:SS") & "','" & Replace(astrSql, "'", "\'") & "')", False)
			End If
		End If
		'Clipboard.Clear
		'Clipboard.SetText astrSql
		
		Executar = lblnRet
		
	End Function
	
	Public Function ExecutarSite(ByVal astrSql As String, Optional ByRef alblnGravaAuditoria As Boolean = False, Optional ByRef adblRowAfetados As Double = 0, Optional ByRef astrRetErro As String = "") As Boolean
		Dim lblnRet As Boolean
		On Error GoTo ErroExecutarSite
		lblnRet = True
		With MyConCSite
			'Call .Execute("START TRANSACTION")
			Call .Execute(astrSql, adblRowAfetados)
			'Call .Execute("COMMIT")
ErroExecutarSite: 
			If .Errors.Count > 0 Then
				astrRetErro = "Código: " & .Errors.Item(.Errors.Count - 1).NativeError & " Descrição: " & .Errors.Item(.Errors.Count - 1).Description
				lblnRet = False
				'Call .Execute("ROLLBACK")
			End If
		End With
		ExecutarSite = lblnRet
	End Function
	
	Public Sub SetaStatusFrame(ByRef afmeAuxiliar As System.Windows.Forms.GroupBox, ByVal ablnModo As Boolean)
		'Rotina para desabilitar e habilitar os campos dentro de um objeto Frame
		Dim ctlControl As System.Windows.Forms.Control
		
		'UPGRADE_WARNING: Control property afmeAuxiliar.Parent was upgraded to afmeAuxiliar.FindForm which has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="DFCDE711-9694-47D7-9C50-45A99CD8E91E"'
		For	Each ctlControl In afmeAuxiliar.FindForm.Controls
			'UPGRADE_WARNING: TypeOf has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
			If Not TypeOf ctlControl Is System.Windows.Forms.Timer Then
				If ctlControl.Parent.Name = afmeAuxiliar.Name Then
					ctlControl.Parent.Enabled = ablnModo
					'UPGRADE_WARNING: TypeOf has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
					If TypeOf ctlControl Is System.Windows.Forms.TextBox Then
						ctlControl.BackColor = System.Drawing.ColorTranslator.FromOle(IIf(ablnModo, System.Drawing.ColorTranslator.ToOle(System.Drawing.SystemColors.Window), System.Drawing.ColorTranslator.ToOle(System.Drawing.SystemColors.Control)))
					End If
					ctlControl.Enabled = ablnModo
				End If
			End If
		Next ctlControl
	End Sub
	
	Public Sub BarraProgresso(ByRef apgbAuxiliar As System.Windows.Forms.ProgressBar, ByRef alblPercentual As System.Windows.Forms.Label, ByRef alblInformacao As System.Windows.Forms.Label, ByVal aintTipo As Short, Optional ByVal alngReg As Integer = 0, Optional ByVal astrMensagem As String = "")
		With apgbAuxiliar
			If aintTipo = 0 Then
				.Minimum = 0
				.Maximum = alngReg
				.Value = 0
			ElseIf aintTipo = 1 Then 
				If .Value < .Maximum Then
					.Value = .Value + 1
					alblPercentual.Text = VB6.Format(Fix((.Value * 100) / .Maximum), "###0") & "%"
					alblInformacao.Text = " Processando" & astrMensagem & ": " & .Value & " até " & .Maximum
				End If
			ElseIf aintTipo = 2 Then 
				alblInformacao.Text = " Processado: " & .Maximum
			End If
		End With
		System.Windows.Forms.Application.DoEvents()
	End Sub
	
	Public Function ChecaNulo(ByRef avarContem As Object, Optional ByRef abTipval As Boolean = False) As Object
		'Esta função devolve o valor recebido caso não seja nulo, e caso for então devolto branco ou o valor 0
		'UPGRADE_WARNING: Couldn't resolve default property of object avarContem. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
		If Not IsDbNull(avarContem) And avarContem <> "" Then
			'UPGRADE_WARNING: Couldn't resolve default property of object avarContem. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			'UPGRADE_WARNING: Couldn't resolve default property of object ChecaNulo. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			ChecaNulo = avarContem
		Else
			If abTipval = False Then
				'UPGRADE_WARNING: Couldn't resolve default property of object ChecaNulo. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
				ChecaNulo = ""
			Else
				'UPGRADE_WARNING: Couldn't resolve default property of object ChecaNulo. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
				ChecaNulo = "0"
			End If
		End If
	End Function
	
	Public Sub LineFeed(ByRef avspRel As AxVSVIEW6.AxVSPrinter, ByVal aintQtdLinhas As Short)
		'Linha em branco repassando o objeto relatorio
		Dim intLinhas As Short
		
		For intLinhas = 1 To aintQtdLinhas
			avspRel.Table = "<199mm;" & "|"
		Next intLinhas
	End Sub
	
	Public Sub IniDoc(ByRef avspCab As AxVSVIEW6.AxVSPrinter, ByVal abEstado As Boolean, Optional ByRef abLandMode As Boolean = False)
		'Esta função controla a inicialização da Vizualização do VSPrinter
		If abEstado = True Then
			If abLandMode = True Then
				avspCab.Orientation = VSVIEW6.OrientationSettings.orLandscape 'Paisagem
			Else
				avspCab.Orientation = VSVIEW6.OrientationSettings.orPortrait 'Retrato
			End If
			avspCab.PageBorder = VSVIEW6.TableBorderSettings.tbNone
			avspCab.TableBorder = VSVIEW6.TableBorderSettings.tbNone
			avspCab.PhysicalPage = True
			avspCab.PaperSize = VSVIEW6.PaperSizeSettings.pprA4
			avspCab.MarginTop = "7mm"
			avspCab.MarginRight = "7mm"
			avspCab.MarginLeft = "7mm"
			avspCab.MarginBottom = "5mm"
			avspCab.MarginFooter = "0mm"
			avspCab.MarginHeader = "0mm"
			avspCab.StartDoc()
		Else
			avspCab.EndDoc()
		End If
	End Sub
	
	Public Sub Cabecalho_Relatorio(ByRef vsCab As AxVSVIEW6.AxVSPrinter, Optional ByRef TituCab As String = "", Optional ByRef SubTituCab As String = "", Optional ByRef TipoCab As String = "", Optional ByRef TipoPapel As Object = Nothing, Optional ByRef SubTituCab2 As String = "")
		Dim strMM As String
		Dim lngMargemAnt As Integer
		Dim lngFontSizeAnt As Integer
		Dim lngLinhaCorrente As Integer
		
		On Error Resume Next
		
		'UPGRADE_WARNING: Couldn't resolve default property of object vsCab.MarginLeft. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		lngMargemAnt = vsCab.MarginLeft
		lngFontSizeAnt = vsCab.Font.SizeInPoints
		vsCab.MarginLeft = "10mm"
		vsCab.Font = VB6.FontChangeName(vsCab.Font, "Arial")
		vsCab.Font = VB6.FontChangeSize(vsCab.Font, 10)
		
		vsCab.TableBorder = VSVIEW6.TableBorderSettings.tbNone
		vsCab.ShowGuides = VSVIEW6.ShowGuideSettings.gdShow
		
		vsCab.TextColor = System.Drawing.Color.Black
		vsCab.BrushStyle = VSVIEW6.BrushStyleSettings.bsSolid
		vsCab.BrushColor = System.Drawing.Color.White
		
		Select Case TipoCab
			Case "1" 'Cabeçalho curto
				vsCab.DrawRectangle("10mm", "10mm", "130mm", "25mm", "1mm")
				vsCab.BrushColor = System.Drawing.ColorTranslator.FromOle(&HE0E0E0)
				vsCab.DrawRectangle("40mm", "10mm", "110mm", "25mm")
				
				Call LineFeed(vsCab, 1)
				
				'Busca Logotipo
				vsCab.DrawPicture(System.Drawing.Image.FromFile(My.Application.Info.DirectoryPath & "\" & LeConfig("ARQUIVO_LOGOTIPO")), "15mm", "11mm", "25mm", "18mm")
				
				vsCab.Table = ">30mm|^75mm|<20mm;||" & VB6.Format(Today, "dd/mm/yy") & ""
				
				vsCab.CurrentY = vsCab.CurrentY - (2 * 119)
				vsCab.Font = VB6.FontChangeSize(vsCab.Font, 12)
				vsCab.Font = VB6.FontChangeBold(vsCab.Font, True)
				vsCab.Table = ">30mm|^75mm|<20mm;|" & TituCab & "|"
				
				vsCab.Font = VB6.FontChangeSize(vsCab.Font, 10)
				vsCab.Font = VB6.FontChangeBold(vsCab.Font, False)
				vsCab.Table = ">30mm|^75mm|<20mm;||" & VB6.Format(TimeOfDay, "HH:mm") & ""
				vsCab.Table = ">30mm|^75mm|<20mm;||Pag.:" & vsCab.PageCount
				
				vsCab.CurrentY = vsCab.CurrentY - (3 * 119)
				vsCab.Font = VB6.FontChangeName(vsCab.Font, "Arial")
				vsCab.Font = VB6.FontChangeSize(vsCab.Font, 10)
				vsCab.Font = VB6.FontChangeBold(vsCab.Font, False)
				vsCab.Table = ">30mm|^75mm|<20mm;|" & SubTituCab & "|"
				
			Case "2" 'Cabeçalho longo
				vsCab.DrawRectangle("10mm", "10mm", "195mm", "30mm", "1mm")
				vsCab.BrushColor = System.Drawing.ColorTranslator.FromOle(&HE0E0E0)
				vsCab.DrawRectangle("45mm", "10mm", "160mm", "30mm")
				
				Call LineFeed(vsCab, 1)
				
				vsCab.DrawPicture(System.Drawing.Image.FromFile(My.Application.Info.DirectoryPath & "\" & LeConfig("ARQUIVO_LOGOTIPO")), "15mm", "11mm", "25mm", "18mm")
				
				vsCab.Font = VB6.FontChangeSize(vsCab.Font, 10)
				vsCab.Font = VB6.FontChangeBold(vsCab.Font, True)
				vsCab.CurrentY = "11mm"
				vsCab.Table = "<50mm|<95mm|>40mm;|" & gstrEmpresa_Nome & "|" & VB6.Format(Today, "dd/mm/yyyy")
				
				vsCab.Font = VB6.FontChangeBold(vsCab.Font, False)
				vsCab.Table = "<50mm|<95mm|>40mm;|" & LeConfig("EMPRESA_ENDERECO") & " - " & gstrEmpresa_Cidade & " - " & gstrEmpresa_UF & "|" & VB6.Format(TimeOfDay, "HH:mm")
				vsCab.Table = "<50mm|<95mm|>40mm;|Fone: " & LeConfig("EMPRESA_FONE") & "     -    " & LeConfig("EMPRESA_SITE") & "|" & "Pag.:" & VB6.Format(vsCab.PageCount, "000")
				
				vsCab.Font = VB6.FontChangeBold(vsCab.Font, True)
				vsCab.Font = VB6.FontChangeSize(vsCab.Font, 9)
				vsCab.Table = "<50mm|^95mm|>40mm;|" & TituCab
				
				vsCab.Font = VB6.FontChangeBold(vsCab.Font, False)
				vsCab.Font = VB6.FontChangeSize(vsCab.Font, 8)
				vsCab.Table = "<50mm|^95mm;|" & SubTituCab
				
				vsCab.Font = VB6.FontChangeSize(vsCab.Font, 10)
				vsCab.CurrentY = "35mm"
				
			Case "3" 'Cabeçalho super longo
				'UPGRADE_WARNING: Couldn't resolve default property of object vsCab.VS. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
				vsCab.VS.MarginLeft = "15mm"
				vsCab.DrawRectangle("10mm", "10mm", "285mm", "30mm", "1mm")
				vsCab.BrushColor = System.Drawing.ColorTranslator.FromOle(&HE0E0E0)
				vsCab.DrawRectangle("40mm", "10mm", "255mm", "30mm")
				
				Call LineFeed(vsCab, 1)
				
				vsCab.DrawPicture(System.Drawing.Image.FromFile(My.Application.Info.DirectoryPath & "\" & LeConfig("ARQUIVO_LOGOTIPO")), "15mm", "11mm", "25mm", "18mm")
				
				vsCab.CurrentY = "11mm"
				vsCab.MarginLeft = "45mm"
				vsCab.Font = VB6.FontChangeSize(vsCab.Font, 14)
				'UPGRADE_WARNING: Couldn't resolve default property of object vsCab.CurrentY. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
				lngLinhaCorrente = vsCab.CurrentY
				vsCab.Table = "^210mm|>25mm;" & TituCab
				
				vsCab.Font = VB6.FontChangeSize(vsCab.Font, 10)
				vsCab.Font = VB6.FontChangeBold(vsCab.Font, False)
				vsCab.CurrentY = lngLinhaCorrente
				vsCab.Table = "^210mm|>25mm;|" & VB6.Format(Today, "dd/mm/yyyy")
				vsCab.Table = "^210mm|>25mm;|" & VB6.Format(TimeOfDay, "HH:mm")
				vsCab.Table = "^210mm|>25mm;" & SubTituCab & "|Pag.:" & vsCab.CurrentPage
				vsCab.Table = "^210mm|>25mm;" & SubTituCab2 & "|"
				vsCab.CurrentY = vsCab.CurrentY + 200
				
			Case "4" 'Cabeçalho A4 Comum
				vsCab.DrawRectangle("15mm", "10mm", "195mm", "30mm", "1mm")
				vsCab.BrushColor = System.Drawing.ColorTranslator.FromOle(&HE0E0E0)
				vsCab.DrawRectangle("45mm", "10mm", "160mm", "30mm")
				
				Call LineFeed(vsCab, 1)
				
				vsCab.DrawPicture(System.Drawing.Image.FromFile(My.Application.Info.DirectoryPath & "\" & LeConfig("ARQUIVO_LOGOTIPO")), "18mm", "11mm", "25mm", "18mm")
				
				vsCab.Font = VB6.FontChangeSize(vsCab.Font, 10)
				vsCab.Font = VB6.FontChangeBold(vsCab.Font, True)
				vsCab.Table = "<50mm|^95mm|>40mm;|" & TituCab & "|" & VB6.Format(Today, "dd/mm/yyyy")
				vsCab.Font = VB6.FontChangeBold(vsCab.Font, False)
				vsCab.Table = "<50mm|^95mm|>40mm;|" & SubTituCab & "|" & VB6.Format(TimeOfDay, "HH:mm")
				vsCab.Table = "<50mm|^95mm|>40mm;|" & SubTituCab2 & "|" & "Pag.:" & VB6.Format(vsCab.PageCount, "000")
				vsCab.CurrentY = vsCab.CurrentY + 200
			Case Else
				strMM = "130mm"
		End Select
		vsCab.MarginLeft = lngMargemAnt
		vsCab.Font = VB6.FontChangeSize(vsCab.Font, lngFontSizeAnt)
	End Sub
	
	Public Function ChecaCodBar(ByVal astrParte As String, ByVal astrCodigo As String) As String
		'Função para pegar dentro do texto do código de barras a identificação selecionada
		Select Case astrParte
			Case "numnf"
				ChecaCodBar = Mid(astrCodigo, 21, 3) & Mid(astrCodigo, 25, 2)
				
			Case "mesano"
				ChecaCodBar = Mid(astrCodigo, 29, 2) & "/" & Mid(astrCodigo, 33, 2)
				
			Case "valor"
				ChecaCodBar = Mid(astrCodigo, 6, 8) & "." & Mid(astrCodigo, 14, 2)
		End Select
	End Function
	
	Public Function ChecaItensServ(ByVal astrServico As String, ByVal astrCampoServ As String) As String
		Dim intPosA As Short
		Dim intPosB As Short
		Dim intPosC As Short
		
		'0302020080?110,34$( 387 x 0,28511 );
		intPosA = 1
		intPosA = InStr(intPosA, astrCampoServ, astrServico)
		If intPosA > 0 Then
			intPosA = InStr(intPosA, astrCampoServ, "?")
			intPosB = InStr(intPosA, astrCampoServ, ";")
			intPosC = InStr(intPosA, astrCampoServ, "$")
			If intPosC > 0 And intPosC < intPosB Then
				ChecaItensServ = CStr(CDbl(Replace(Mid(astrCampoServ, intPosA + 1, intPosC - intPosA - 1), ".", ",")))
			Else
				ChecaItensServ = CStr(CDbl(Replace(Mid(astrCampoServ, intPosA + 1, intPosB - intPosA - 1), ".", ",")))
			End If
			intPosA = intPosB
		Else
			ChecaItensServ = CStr(0)
		End If
	End Function
	
	Public Sub LimpaCampos(ByRef aframeBastidor As System.Windows.Forms.GroupBox)
		'Função para limpar o conteúdo dos campos do tipo TextBox dentro de objeto Frame
		Dim intCampos As Short
		
		'UPGRADE_WARNING: Control property aframeBastidor.Parent was upgraded to aframeBastidor.FindForm which has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="DFCDE711-9694-47D7-9C50-45A99CD8E91E"'
		'UPGRADE_WARNING: Controls method Parent.Controls.Count has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6BA9B8D2-2A32-4B6E-8D36-44949974A5B4"'
		For intCampos = 0 To aframeBastidor.FindForm.Controls.Count() - 1
			'UPGRADE_WARNING: Control property aframeBastidor.Parent was upgraded to aframeBastidor.FindForm which has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="DFCDE711-9694-47D7-9C50-45A99CD8E91E"'
			'UPGRADE_WARNING: TypeOf has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
			If TypeOf CType(aframeBastidor.FindForm.Controls(intCampos), Object) Is System.Windows.Forms.TextBox Then
				'UPGRADE_WARNING: Control property aframeBastidor.Parent was upgraded to aframeBastidor.FindForm which has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="DFCDE711-9694-47D7-9C50-45A99CD8E91E"'
				CType(aframeBastidor.FindForm.Controls(intCampos), Object).Text = ""
			End If
		Next intCampos
	End Sub
	
	Public Sub LimpaCamposObjeto(ByRef aobjAux As Object)
		Dim lctlAux As System.Windows.Forms.Control
		'UPGRADE_WARNING: Couldn't resolve default property of object aobjAux.Parent. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		For	Each lctlAux In aobjAux.Parent.Controls
			'UPGRADE_WARNING: Couldn't resolve default property of object aobjAux.Name. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			If lctlAux.Parent.Name = aobjAux.Name Then
				'UPGRADE_WARNING: TypeOf has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
				If TypeOf lctlAux Is System.Windows.Forms.TextBox Then
					lctlAux.Text = ""
					'UPGRADE_WARNING: TypeOf has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
				ElseIf TypeOf lctlAux Is System.Windows.Forms.CheckBox Then 
					'UPGRADE_WARNING: Couldn't resolve default property of object lctlAux.value. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					lctlAux.value = System.Windows.Forms.CheckState.Unchecked
					'UPGRADE_WARNING: TypeOf has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
				ElseIf TypeOf lctlAux Is System.Windows.Forms.ComboBox Then 
					'UPGRADE_WARNING: Couldn't resolve default property of object lctlAux.ListIndex. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					lctlAux.ListIndex = 0
				End If
			End If
		Next lctlAux
	End Sub
	
	Public Function virgToPonto(ByVal astrValor As String) As String
		'Função para trocar o caracter virgula por ponto - Rídiculo
		Dim intPosA As Short
		Dim strValor As String
		
		intPosA = InStr(1, astrValor, ",")
		
		If intPosA > 0 Then
			strValor = Mid(astrValor, 1, intPosA - 1) & "." & Mid(astrValor, intPosA + 1, Len(astrValor) - (intPosA))
		End If
		
		virgToPonto = strValor
	End Function
	
	Public Function codTodescri(ByVal astrCod As String) As String
		'Função que retorna a descrição do código selecionado da tabela de códigos
		Dim lstrRet As String
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrRet = ""
		lstrSql = "SELECT * FROM " & gstrDataBase & ".`codigos` WHERE `num` = '" & astrCod & "'"
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrRet = IIf(IsDbNull(.Fields("descri").value), astrCod, .Fields("descri").value)
				Else
					lstrRet = astrCod
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		codTodescri = lstrRet
	End Function
	
	Public Function BuscaDescricaoCodido(ByVal astrCodigo As String) As String
		Dim lstrRet As String
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrRet = ""
		lstrSql = ""
		lstrSql = lstrSql & "SELECT * "
		lstrSql = lstrSql & "  FROM " & gstrDataBase & ".`codigos` "
		lstrSql = lstrSql & " WHERE `num` = '" & astrCodigo & "' "
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrRet = Trim(IIf(IsDbNull(.Fields("descri").value), "", .Fields("descri").value))
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		BuscaDescricaoCodido = lstrRet
	End Function
	
	Public Function BuscaValorCodigo(ByVal astrCodigo As String) As Double
		Dim ldblRet As Double
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrSql = ""
		lstrSql = lstrSql & "SELECT * "
		lstrSql = lstrSql & "  FROM " & gstrDataBase & ".`codigos` "
		lstrSql = lstrSql & " WHERE `num` = '" & astrCodigo & "' "
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					ldblRet = CDbl(IIf(IsDbNull(.Fields("valor").value), 0, .Fields("valor").value))
				Else
					ldblRet = 0
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		BuscaValorCodigo = ldblRet
	End Function
	
	Public Function TarifaToDescri(ByVal astrCod As String) As String
		'Função que retorna a descrição do código selecionado da tabela de códigos
		Dim lstrRet As String
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrSql = "SELECT * FROM `tarifa` WHERE `num` = '" & astrCod & "' ORDER BY STR_TO_DATE(`datanova`,'%d/%m/%Y%') DESC LIMIT 0, 1"
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrRet = Trim(IIf(IsDbNull(.Fields("descri").value), astrCod, .Fields("descri").value))
				Else
					lstrRet = astrCod
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		TarifaToDescri = lstrRet
	End Function
	
	Public Function TarifaToLimitkWh(ByVal astrCod As String) As String
		'Função que retorna a descrição do código selecionado da tabela de códigos
		Dim lstrRet As String
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrSql = "SELECT * FROM `tarifa` WHERE `num` = '" & astrCod & "' ORDER BY STR_TO_DATE(`datanova`,'%d/%m/%Y%') DESC LIMIT 0, 1"
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrRet = Trim(IIf(IsDbNull(.Fields("limitkwh").value), "", .Fields("limitkwh").value))
				Else
					lstrRet = ""
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		TarifaToLimitkWh = lstrRet
	End Function
	
	Public Function OnOffProcMon(ByVal onSet As Boolean, Optional ByVal astrAviso As String = "", Optional ByVal aintMax As Short = 0) As Object
		'Função para mostra aquela telinha amarela caganerra na tela!!
		'É usado em conjunto
		If Len(Trim(astrAviso)) < 1 Then astrAviso = gstrTituloMensagem
		If onSet = True Then
			frmProcessoMon.ProgressBar1.Minimum = 0
			frmProcessoMon.ProgressBar1.Maximum = aintMax + 1
			frmProcessoMon.ProgressBar1.Value = frmProcessoMon.ProgressBar1.Minimum
			frmProcessoMon.LSituacao.Text = astrAviso
			frmProcessoMon.Show()
		Else
			If astrAviso = "soma" Then
				frmProcessoMon.ProgressBar1.Value = frmProcessoMon.ProgressBar1.Value + 1
			Else
				frmProcessoMon.LSituacao.Text = ""
				frmProcessoMon.Hide()
			End If
		End If
	End Function
	
	Public Function BuscaNomeUC(ByVal alngConsId As Integer, ByVal alngUnidId As Integer, ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String) As String
		Dim lstrRet As String
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrRet = ""
		lstrSql = ""
		lstrSql = lstrSql & "    SELECT consum.consreg, IFNULL(IFNULL(unida.nome,unidb.nome),consum.nome) `nomeuc` "
		lstrSql = lstrSql & "      FROM " & gstrDataBase & ".`consum` "
		lstrSql = lstrSql & " LEFT JOIN `unidb` ON(unidb.zona  = '" & astrZona & "' AND "
		lstrSql = lstrSql & "                      unidb.livro = '" & astrLivro & "' AND "
		lstrSql = lstrSql & "                      unidb.conta = '" & astrConta & "' AND "
		lstrSql = lstrSql & "                      unidb.cons_id = consum.consreg AND "
		lstrSql = lstrSql & "                      unidb.unid_id = " & alngUnidId & ") "
		lstrSql = lstrSql & " LEFT JOIN `unida` ON(unida.zona  = '" & astrZona & "' AND "
		lstrSql = lstrSql & "                      unida.livro = '" & astrLivro & "' AND "
		lstrSql = lstrSql & "                      unida.conta = '" & astrConta & "' AND "
		lstrSql = lstrSql & "                      unida.cons_id = consum.consreg AND "
		lstrSql = lstrSql & "                      unida.unid_id = " & alngUnidId & ") "
		lstrSql = lstrSql & "     WHERE consum.consreg = " & alngConsId
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrRet = Trim(IIf(IsDbNull(.Fields("nomeuc").value), "", .Fields("nomeuc").value))
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		BuscaNomeUC = lstrRet
	End Function
	
	Public Sub BuscaCodItem(ByRef I As Integer, ByVal itemNF As String)
		Dim PServ As String
		Dim PVal As Integer
		Dim PCif As Integer
		Dim posA As Integer
		Dim posB As Integer
		Dim posC As Integer
		RefCodServ = ""
		PServ = CStr(InStr(I, Trim(itemNF), "?"))
		PVal = InStr(CShort(PServ), itemNF, ";")
		PCif = InStr(CShort(PServ), itemNF, "$")
		If PVal > PCif And PCif > 0 Then
			RefCodServ = Mid(itemNF, PCif + 1, (PVal - PCif) - 1)
		End If
		posA = (CDbl(PServ) - I) '- 1
		posB = (PVal - CDbl(PServ)) - 1
		posC = (PCif - CDbl(PServ)) - 1
		If posC <= 0 Then posC = posB
		codserv = Mid(itemNF, I, posA)
		VlrCodServ = Mid(itemNF, CDbl(PServ) + 1, IIf(posB <= posC, posB, posC))
		VlrCodServ = Replace(VlrCodServ, ",", ".")
		IndCodServ = PVal
	End Sub
	
	Public Function Extenso(ByVal valor As Double, ByVal MoedaPlural As String, ByVal MoedaSingular As String) As String
		Dim strValor As String
		Dim Negativo As Boolean
		Dim Buf As String
		Dim Parcial As Short
		Dim Posicao As Short
		Dim Unidades As Object
		Dim Dezenas As Object
		Dim Centenas As Object
		Dim PotenciasSingular As Object
		Dim PotenciasPlural As Object
		'
		Negativo = (valor < 0)
		valor = System.Math.Abs(CDec(valor))
		If valor Then
			'UPGRADE_WARNING: Array has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
			'UPGRADE_WARNING: Couldn't resolve default property of object Unidades. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			Unidades = New Object(){vbNullString, "Um", "Dois", "Três", "Quatro", "Cinco", "Seis", "Sete", "Oito", "Nove", "Dez", "Onze", "Doze", "Treze", "Quatorze", "Quinze", "Dezesseis", "Dezessete", "Dezoito", "Dezenove"}
			'UPGRADE_WARNING: Array has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
			'UPGRADE_WARNING: Couldn't resolve default property of object Dezenas. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			Dezenas = New Object(){vbNullString, vbNullString, "Vinte", "Trinta", "Quarenta", "Cinqüenta", "Sessenta", "Setenta", "Oitenta", "Noventa"}
			'UPGRADE_WARNING: Array has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
			'UPGRADE_WARNING: Couldn't resolve default property of object Centenas. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			Centenas = New Object(){vbNullString, "Cento", "Duzentos", "Trezentos", "Quatrocentos", "Quinhentos", "Seiscentos", "Setecentos", "Oitocentos", "Novecentos"}
			'UPGRADE_WARNING: Array has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
			'UPGRADE_WARNING: Couldn't resolve default property of object PotenciasSingular. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			PotenciasSingular = New Object(){vbNullString, " Mil", " Milhão", " Bilhão", " Trilhão", " Quatrilhão"}
			'UPGRADE_WARNING: Array has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"'
			'UPGRADE_WARNING: Couldn't resolve default property of object PotenciasPlural. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
			PotenciasPlural = New Object(){vbNullString, " Mil", " Milhões", " Bilhões", " Trilhões", " Quatrilhões"}
			
			strValor = Left(VB6.Format(valor, New String("0", 18) & ".000"), 18)
			For Posicao = 1 To 18 Step 3
				Parcial = Val(Mid(strValor, Posicao, 3))
				If Parcial Then
					If Parcial = 1 Then
						'UPGRADE_WARNING: Couldn't resolve default property of object PotenciasSingular(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
						Buf = "Um" & PotenciasSingular((18 - Posicao) \ 3)
					ElseIf Parcial = 100 Then 
						'UPGRADE_WARNING: Couldn't resolve default property of object PotenciasSingular(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
						Buf = "Cem" & PotenciasSingular((18 - Posicao) \ 3)
					Else
						'UPGRADE_WARNING: Couldn't resolve default property of object Centenas(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
						Buf = Centenas(Parcial \ 100)
						Parcial = Parcial Mod 100
						If Parcial <> 0 And Buf <> vbNullString Then
							Buf = Buf & " e "
						End If
						If Parcial < 20 Then
							'UPGRADE_WARNING: Couldn't resolve default property of object Unidades(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
							Buf = Buf & Unidades(Parcial)
						Else
							'UPGRADE_WARNING: Couldn't resolve default property of object Dezenas(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
							Buf = Buf & Dezenas(Parcial \ 10)
							Parcial = Parcial Mod 10
							If Parcial <> 0 And Buf <> vbNullString Then
								Buf = Buf & " e "
							End If
							'UPGRADE_WARNING: Couldn't resolve default property of object Unidades(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
							Buf = Buf & Unidades(Parcial)
						End If
						'UPGRADE_WARNING: Couldn't resolve default property of object PotenciasPlural(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
						Buf = Buf & PotenciasPlural((18 - Posicao) \ 3)
					End If
					If Buf <> vbNullString Then
						If Extenso <> vbNullString Then
							Parcial = Val(Mid(strValor, Posicao, 3))
							If Posicao = 16 And (Parcial < 100 Or (Parcial Mod 100) = 0) Then
								Extenso = Extenso & " e "
							Else
								Extenso = Extenso & ", "
							End If
						End If
						Extenso = Extenso & Buf
					End If
				End If
			Next 
			If Extenso <> vbNullString Then
				If Negativo Then
					Extenso = "Menos " & Extenso
				End If
				If Int(valor) = 1 Then
					Extenso = Extenso & " " & MoedaSingular
				Else
					Extenso = Extenso & " " & MoedaPlural
				End If
			End If
			Parcial = Int((valor - Int(valor)) * 100 + 0.1)
			If Parcial Then
				Buf = Extenso(Parcial, "Centavos", "Centavo")
				If Extenso <> vbNullString Then
					Extenso = Extenso & " e "
				End If
				Extenso = Extenso & Buf
			End If
		End If
	End Function
	
	Public Function FData(ByVal astrData As String) As String
		'## ESTA FUNÇÃO EXECUTA FORMATAÇÃO DE DATA ##########
		Dim lstrRet As String
		Dim lintTam As Short
		lintTam = CShort(Len(astrData))
		If lintTam = 1 And CDbl(Mid(astrData, 1, 1)) = 0 Then
			Call MsgBox("Data não pode ser ( 0 ) zero ", MsgBoxStyle.Exclamation, gstrTituloMensagem)
		Else
			Select Case lintTam
				Case 1, 2
					' EX: 1 ou 01 - NO CAMPO DATA INFORMA SOMENTE O DIA E A FUNÇÃO COMPLEMENTA COM MES/ANO CORRENTE = 01/01/2006
					lstrRet = VB6.Format(VB6.Format(astrData, "00") & "/" & Month(Today) & "/" & Year(Today), "DD/MM/YYYY")
				Case 4
					'EX: 0101 - No campo Data Informe dia e mes e a função complementa com o ano corrente = 01/01/2006
					lstrRet = VB6.Format(Mid(astrData, 1, 2) & "/" & Mid(astrData, 3, 2) & "/" & Year(Today), "DD/MM/YYYY")
				Case 6, 8
					' EX: 010106 ou 01012006
					lstrRet = VB6.Format(Mid(astrData, 1, 2) & "/" & Mid(astrData, 3, 2) & "/" & Mid(astrData, 5), "DD/MM/YYYY")
				Case Else
					lstrRet = astrData
			End Select
			If Len(lstrRet) > 0 Then
				If Not IsDate(lstrRet) Then
					Call MsgBox("Data inválida!", MsgBoxStyle.Exclamation, gstrTituloMensagem)
					lstrRet = ""
				End If
			End If
		End If
		FData = lstrRet
	End Function
	
	Public Function LeConfig(ByVal astrParametro As String) As String
		'LÊ UM PARÂMETRO DE CONFIGURAÇÃO NO BANCO DE DADOS DA TABELA 'CONFIG'.
		'VALORES DE RETORNO:
		'** "-1" SE NÃO ENCONTRA O PARÂMETRO
		'** O VALOR ENCONTRADO
		Dim lstrValor As String
		Dim lstrSql As String
		Dim lrstConfig As ADODB.Recordset
		lrstConfig = New ADODB.Recordset
		lstrSql = ""
		lstrSql = lstrSql & "SELECT * "
		lstrSql = lstrSql & "  FROM `config` "
		lstrSql = lstrSql & " WHERE `nomepar` = '" & Replace(astrParametro, "'", "\'") & "';"
		Call Conectar(lstrSql, lrstConfig, False)
		With lrstConfig
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount = 1 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrValor = Trim(IIf(IsDbNull(.Fields("valorPar").value), "", .Fields("valorPar").value))
				Else
					lstrValor = "-1"
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstConfig may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstConfig = Nothing
		LeConfig = lstrValor
	End Function
	
	Public Function GravaConfig(ByVal astrNome As String, ByVal astrValor As String) As Short
		'GRAVA O VALOR NO PARÂMETRO INDICADO NA TABELA CONFIG.
		'VALORES DE RETORNO:
		'** 1 SE GRAVOU COM SUCESSO
		'** -1 SE HOUVE ERRO NA GRAVAÇÃO
		Dim lstrSql As String
		
		On Error GoTo ErroGravaConfig
		lstrSql = "UPDATE config SET " & "       config.valorpar = """ & Trim(astrValor) & """ " & " WHERE config.nomepar = """ & UCase(astrNome) & """ "
		Call Executar(lstrSql)
		GravaConfig = 1
		Exit Function
ErroGravaConfig: 
		GravaConfig = -1
	End Function
	
	Public Function CriaParConfig(ByVal astrNome As String, ByVal astrValor As String, Optional ByVal ablnEdita As Boolean = False, Optional ByVal astrDescr As String = "") As Short
		'CRIA UM NOVO VALOR DE PARÂMETRO INDICADO NA TABELA CONFIG.
		'VALORES DE RETORNO:
		'** 1 SE GRAVOU COM SUCESSO
		'** -1 SE HOUVE ERRO NA GRAVAÇÃO
		Dim lstrSql As String
		Dim lstrFlag As String
		
		On Error GoTo ErroCriaPar
		
		lstrFlag = IIf(ablnEdita, "S", "N")
		If Len(Trim(astrDescr)) < 1 Then astrDescr = ""
		
		lstrSql = "INSERT INTO config SET " & "            config.nomepar   = """ & UCase(astrNome) & """, " & "            config.valorpar  = """ & Trim(astrValor) & """, " & "            config.flag      = """ & lstrFlag & """, " & "            config.desc      = """ & astrDescr & """; "
		Call Executar(lstrSql)
		CriaParConfig = 1
		Exit Function
ErroCriaPar: 
		CriaParConfig = -1
	End Function
	
	Public Function FormataData(ByVal t As System.Windows.Forms.TextBox, ByVal formato As Short) As String
		't: textbox a ser formatada
		
		'formato: constante - 1 para MM/AAAA, 2 para DD/MM/AAAA
		
		'exemplos de funcionamento, imaginando mes/ano atual = 10/2006
		'considera-se como entrada a sequencia de numeros, eliminando
		'quaisquer caracteres estranhos.
		
		'entrada    saida (1)   saida (2)
		'1          01/2006     01/10/2006 -
		'9          09/2006     09/10/2006  |saida 1 conta como mes,
		'12         12/2006     12/10/2006  |saida 2 conta como dia
		'31         invalido    31/10/2006 -
		'123        invalido    invalido
		'012        invalido    invalido
		'0106       01/2006     01/06/2006
		'3107       invalido    31/07/2006
		'2006       invalido    20/06/2006
		'1221       12/2021     invalido
		'12006      invalido    invalido
		'052006     05/2006     invalido
		'202005     invalido    invalido
		'031206     03/1206     03/12/2006
		'1122009    invalido    invalido
		'01042004   invalido    01/04/2004
		'31042004   invalido    30/04/2004
		'30022005   invalido    28/02/2005
		'30022000   invalido    29/02/2000 (ano bissexto)
		'10132007   invalido    invalido
		
		Dim dia As Short
		Dim mes As Short
		Dim ano As Short
		Dim result As String
		Dim aux As String
		Dim auxnum As Integer
		Dim auxdia As String
		Dim auxmes As String
		Dim auxano As String
		
		If (formato < 1) Or (formato > 2) Then Exit Function
		
		aux = Replace(t.Text, "/", "")
		aux = Replace(aux, "-", "")
		aux = Replace(aux, ".", "")
		aux = Replace(aux, " ", "")
		
		ano = CShort(VB6.Format(Today, "yyyy"))
		mes = CShort(VB6.Format(Today, "mm"))
		
		If Not IsNumeric(aux) Then
			t.Text = ""
			Exit Function
		Else
			If aux = "" Then
				auxnum = 0
			Else
				auxnum = Val(aux)
			End If
		End If
		
		If formato = 1 Then 'DD/AAAA
			Select Case Len(aux)
				Case 1
					If Val(aux) <= 12 And Val(aux) >= 1 Then
						result = VB6.Format(aux, "00") & "/" & VB6.Format(Today, "yyyy")
					Else
						result = ""
					End If
				Case 2
					If Val(aux) <= 12 And Val(aux) >= 1 Then
						result = VB6.Format(aux, "00") & "/" & VB6.Format(Today, "yyyy")
					Else
						result = ""
					End If
				Case 4 'conta como mes/ano
					mes = Val(Mid(aux, 1, 2))
					If Val(Mid(aux, 3, 2)) > 49 Then
						ano = Val("19" & Mid(aux, 3, 2))
					Else
						ano = Val("20" & Mid(aux, 3, 2))
					End If
					If mes <= 12 And mes >= 1 Then
						result = VB6.Format(mes, "00") & "/" & VB6.Format(ano, "0000")
					Else
						result = ""
					End If
				Case 6 ' conta como mes/ano
					mes = Val(Mid(aux, 1, 2))
					If mes >= 1 And mes <= 12 Then
						result = VB6.Format(mes, "00") & "/" & VB6.Format(Mid(aux, 3), "0000")
					Else
						result = ""
					End If
				Case Else
					result = ""
			End Select
		Else
			Select Case Len(aux)
				Case 1
					If Val(aux) <= 12 And Val(aux) >= 1 Then
						result = VB6.Format(aux, "00") & "/" & VB6.Format(Today, "mm/yyyy")
					Else
						result = ""
					End If
				Case 2
					If Val(aux) >= 1 And Val(aux) <= 30 Then
						result = VB6.Format(aux, "00") & "/" & VB6.Format(Today, "mm/yyyy")
					Else
						If Val(aux) > 0 Then
							result = VB6.Format(UltimoDiaMes(mes, ano), "00") & "/" & VB6.Format(Today, "mm/yyyy")
						Else
							result = ""
						End If
					End If
				Case 4 'conta como dia/mes + ano
					dia = Val(Mid(aux, 1, 2))
					mes = Val(Mid(aux, 3, 2))
					If mes < 1 Or mes > 12 Then
						mes = Val(VB6.Format(Today, "mm"))
					End If
					
					If dia = 0 Then
						dia = Val(VB6.Format(Today, "dd"))
					Else
						If dia > 30 Then
							dia = UltimoDiaMes(mes, ano)
						End If
					End If
					result = VB6.Format(dia, "00") & "/" & VB6.Format(mes, "00") & "/" & VB6.Format(ano, "0000")
				Case 6 'conta como dia/mes/ano
					dia = Val(Mid(aux, 1, 2))
					mes = Val(Mid(aux, 3, 2))
					ano = Val(Mid(aux, 5))
					If ano < 49 Then
						auxano = "20" & Mid(aux, 5)
					Else
						auxano = "19" & Mid(aux, 5)
					End If
					If mes < 1 Or mes > 12 Then
						auxmes = VB6.Format(Today, "mm")
					Else
						auxmes = VB6.Format(mes, "00")
					End If
					If dia < 1 Or dia > 30 Then
						If dia = 0 Then
							auxdia = VB6.Format(Today, "dd")
						Else
							auxdia = VB6.Format(UltimoDiaMes(mes, ano), "00")
						End If
					Else
						auxdia = VB6.Format(dia, "00")
					End If
					result = auxdia & "/" & auxmes & "/" & auxano
				Case 8
					dia = Val(Mid(aux, 1, 2))
					mes = Val(Mid(aux, 3, 2))
					auxano = Mid(aux, 5)
					If mes < 1 Or mes > 12 Then
						auxmes = VB6.Format(Today, "mm")
					Else
						auxmes = VB6.Format(mes, "00")
					End If
					If dia < 1 Or dia > 30 Then
						If dia = 0 Then
							auxdia = VB6.Format(Today, "dd")
						Else
							auxdia = VB6.Format(UltimoDiaMes(mes, ano), "00")
						End If
					Else
						auxdia = VB6.Format(dia, "00")
					End If
					result = auxdia & "/" & auxmes & "/" & auxano
					If Not IsDate(result) Then
						Call MsgBox("Data inválida", MsgBoxStyle.Exclamation, gstrTituloMensagem)
						result = ""
					End If
				Case Else
					result = ""
			End Select
		End If
		FormataData = result
	End Function
	
	Public Function UltimoDiaMes(ByRef mes As Short, ByRef ano As Short) As Short
		UltimoDiaMes = VB.Day(System.Date.FromOADate(DateSerial(ano, mes + 1, 1).ToOADate - 1))
	End Function
	
	Public Sub CalculaMultaJuros(ByRef astrZona As String, ByRef astrLivro As String, ByRef astrConta As String, ByRef mesano As String, Optional ByRef alngConsId As Integer = 0, Optional ByRef alngUnidId As Integer = 0)
		Dim dtPgto As Date
		Dim dtVcto As Date
		Dim dtVerif As Date
		Dim mesPgto As Short
		Dim anoPgto As Short
		Dim mesVcto As Short
		Dim anoVcto As Short
		Dim diasAtraso As Short
		Dim percMulta As Double
		Dim vlrMulta As Double
		Dim percJuros As Double
		Dim vlrJuros As Double
		Dim vlrCM As Double
		Dim vlrNota As Double
		Dim strsql As String
		Dim dtLoop As Date
		Dim vlrIlum As Double
		Dim vlrConv As Double
		Dim vlrMultAnt As Double
		Dim vlrJuroAnt As Double
		Dim vlrCorrAnt As Double
		Dim vlrIsentoMulta As Double
		Dim strCobrado As String
		Dim strMesAno As String
		Dim intSemana As Short
		Dim bFeriado As Boolean
		Dim lintQtdFeriado As Short
		
		Dim rsFatura As ADODB.Recordset
		Dim rsMultaJuro As ADODB.Recordset
		
		
		rsFatura = New ADODB.Recordset
		rsMultaJuro = New ADODB.Recordset
		
		bFeriado = False
		dtVerif = CDate("01/" & mesano)
		
		If gstrEmpresa_Sigla = "COORSEL" And CInt(Right(mesano, 4) & Left(mesano, 2)) <= 200806 Then
			dtVerif = CDate("25/06/2008")
		ElseIf gstrEmpresa_Sigla = "EFLJCL" And CInt(Right(mesano, 4) & Left(mesano, 2)) <= 200904 Then 
			dtVerif = CDate("30/04/2009")
		ElseIf gstrEmpresa_Sigla = "CERGAL" And CInt(Right(mesano, 4) & Left(mesano, 2)) <= 200908 Then 
			dtVerif = CDate("25/08/2009")
		Else
			dtVerif = CDate("01/" & mesano)
		End If
		strsql = ""
		strsql = strsql & "  SELECT * "
		strsql = strsql & "    FROM nf "
		strsql = strsql & "   WHERE flgst = 'P' "
		strsql = strsql & "     AND zona = '" & astrZona & "' "
		strsql = strsql & "     AND livro = '" & astrLivro & "' "
		strsql = strsql & "     AND conta = '" & astrConta & "' "
		If alngConsId > 0 Then
			strsql = strsql & "     AND cons_id = '" & alngConsId & "' "
		End If
		If alngUnidId > 0 Then
			strsql = strsql & "     AND unid_id = '" & alngUnidId & "' "
		End If
		strsql = strsql & "     AND datapag >= '" & VB6.Format(dtVerif, "yyyy-MM-dd") & "'"
		strsql = strsql & "     AND datapag > datavenc  "
		strsql = strsql & "ORDER BY mesano_ref asc"
		Call Conectar(strsql, rsFatura)
		If rsFatura.RecordCount > 0 Then
			'só calcula juros e correcao se a nota fiscal não estiver em aberto.
			While Not rsFatura.EOF
				strsql = ""
				strsql = strsql & "SELECT * "
				strsql = strsql & "  FROM multajuros "
				strsql = strsql & " WHERE zona = '" & rsFatura.Fields("zona").value & "' "
				strsql = strsql & "   AND livro = '" & rsFatura.Fields("livro").value & "' "
				strsql = strsql & "   AND conta = '" & rsFatura.Fields("conta").value & "' "
				strsql = strsql & "   AND mesano = '" & rsFatura.Fields("mesano").value & "'"
				If alngConsId > 0 Then
					strsql = strsql & "   AND cons_id = '" & alngConsId & "' "
				End If
				If alngUnidId > 0 Then
					strsql = strsql & "   AND unid_id = '" & alngUnidId & "' "
				End If
				strsql = strsql & "   AND numnf = '" & rsFatura.Fields("numnf").value & "' "
				Call Conectar(strsql, rsMultaJuro)
				If rsMultaJuro.RecordCount < 1 Then
					If rsMultaJuro.State = 1 Then Call rsMultaJuro.Close()
					vlrCM = 0
					vlrJuros = 0
					vlrMulta = 0
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					If Not IsDbNull(rsFatura.Fields("datapag").Value) Then
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						vlrIlum = BuscaVlrItem(IIf(IsDbNull(rsFatura.Fields("itensserv").Value), "", rsFatura.Fields("itensserv").Value), "0301000003")
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						vlrConv = BuscaVlrItem(IIf(IsDbNull(rsFatura.Fields("itensserv").Value), "", rsFatura.Fields("itensserv").Value), "903000")
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						vlrMultAnt = BuscaVlrItem(IIf(IsDbNull(rsFatura.Fields("itensserv").Value), "", rsFatura.Fields("itensserv").Value), "9080000061")
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						vlrJuroAnt = BuscaVlrItem(IIf(IsDbNull(rsFatura.Fields("itensserv").Value), "", rsFatura.Fields("itensserv").Value), "9080000066")
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						vlrCorrAnt = BuscaVlrItem(IIf(IsDbNull(rsFatura.Fields("itensserv").Value), "", rsFatura.Fields("itensserv").Value), "9080000067")
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						vlrIsentoMulta = BuscaVlrItem(IIf(IsDbNull(rsFatura.Fields("itensserv").Value), "", rsFatura.Fields("itensserv").Value), "908001")
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						vlrNota = IIf(IsDbNull(rsFatura.Fields("ValorTot").Value), 0, rsFatura.Fields("ValorTot").Value)
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						strMesAno = IIf(IsDbNull(rsFatura.Fields("mesano").Value), mesano, rsFatura.Fields("mesano").Value)
						If vlrNota > 0 Then
							vlrNota = vlrNota - (vlrIlum + vlrConv + vlrMultAnt + vlrJuroAnt + vlrCorrAnt + vlrIsentoMulta)
							If vlrNota < 0 Then
								vlrNota = 0
							End If
						End If
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						dtPgto = CDate(VB6.Format(IIf(IsDbNull(rsFatura.Fields("datapag").Value), "0000-00-00", rsFatura.Fields("datapag").Value), "dd/mm/yyyy"))
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						dtVcto = CDate(VB6.Format(IIf(IsDbNull(rsFatura.Fields("datavenc").Value), "0000-00-00", rsFatura.Fields("datavenc").Value), "dd/mm/yyyy"))
						'UPGRADE_WARNING: DateDiff behavior may be different. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6B38EC3F-686D-4B2E-B5A5-9E8E7A762E32"'
						diasAtraso = DateDiff(Microsoft.VisualBasic.DateInterval.Day, dtVcto, dtPgto)
						intSemana = WeekDay(dtVcto, FirstDayOfWeek.Sunday)
						dtLoop = dtVcto
						lintQtdFeriado = 0
						While dtLoop <= dtPgto
							If WeekDay(dtLoop, FirstDayOfWeek.Sunday) <> 7 And WeekDay(dtLoop, FirstDayOfWeek.Sunday) <> 1 Then
								If VerificaFeriado(dtLoop) Then
									lintQtdFeriado = lintQtdFeriado + 1
								End If
							End If
							dtLoop = System.Date.FromOADate(dtLoop.ToOADate + 1)
						End While
						diasAtraso = diasAtraso - lintQtdFeriado
						bFeriado = VerificaFeriado(dtVcto)
						'Verifica se é Sábado, Domingo e Feriado se for entao nao cobra multa e juro
						If (diasAtraso < 3 And intSemana = 7) Or (diasAtraso < 2 And intSemana = 1) Or (diasAtraso < 4 And bFeriado) Then
							vlrJuros = 0
							vlrCM = 0
						Else
							If diasAtraso > 0 Then
								'calculando juros de acordo com a config
								percJuros = CDbl(LeConfig("PERCENTUALJUROS")) / 100
								vlrJuros = ((vlrNota * percJuros) / 365) * diasAtraso
								'calculando correcao monetaria diaria
								'isso facilita a vida do cabra E usa um recurso
								'ótimo do VB, que é o loop com variável DATE.
								dtLoop = dtVcto
								vlrCM = 0
								While dtLoop <= dtPgto
									vlrCM = vlrCM + (vlrNota * IndiceCMDia(CShort(Month(dtLoop)), CShort(Year(dtLoop))))
									dtLoop = System.Date.FromOADate(dtLoop.ToOADate + 1)
								End While
							End If
						End If
					End If
					
					'pesquisa se tem multas anteriores:
					'pode acontecer de já haver um registro na tabela por conta de cobrar multa de faturas em aberto
					strsql = ""
					strsql = strsql & "SELECT * "
					strsql = strsql & "  FROM multajuros "
					strsql = strsql & " WHERE zona = '" & astrZona & "' "
					strsql = strsql & "   AND livro = '" & astrLivro & "' "
					strsql = strsql & "   AND conta = '" & astrConta & "' "
					If alngConsId > 0 Then
						strsql = strsql & "   AND cons_id = '" & alngConsId & "' "
					End If
					If alngUnidId > 0 Then
						strsql = strsql & "   AND unid_id = '" & alngUnidId & "' "
					End If
					strsql = strsql & "   AND mesano = '" & strMesAno & "'"
					Call Conectar(strsql, rsMultaJuro)
					strCobrado = "N"
					If rsMultaJuro.RecordCount > 0 Then
						'existe registro de multa pra essa nota,
						'checar se foi cobrada. se não foi cobrada,
						'deleta o registro e calcula normalmente.
						'se foi cobrada, não cobra a multa e cobra
						'juros e correcao.\
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						strCobrado = IIf(IsDbNull(rsMultaJuro.Fields("cobrado").Value), "N", rsMultaJuro.Fields("cobrado").Value)
						strCobrado = IIf(Len(Trim(strCobrado)) = 0, "N", strCobrado)
						If strCobrado = "N" Then
							strsql = "DELETE FROM multajuros WHERE codigo = " & rsMultaJuro.Fields("codigo").Value & ";"
							Call Executar(strsql)
							'calculando multa de acordo com a config
							percMulta = CDbl(LeConfig("MULTA")) / 100
							vlrMulta = vlrNota * percMulta
						End If
					Else
						If (diasAtraso < 3 And intSemana = 7) Or (diasAtraso < 2 And intSemana = 1) Or (diasAtraso < 4 And bFeriado) Then
							vlrMulta = 0
						Else
							If diasAtraso > 0 Then
								'se não tiver nenhuma multa, calcular agora.
								'calculando multa de acordo com a config
								percMulta = CDbl(LeConfig("MULTA")) / 100
								vlrMulta = vlrNota * percMulta
							End If
						End If
					End If
					If rsMultaJuro.State = 1 Then rsMultaJuro.Close()
					If (diasAtraso < 3 And intSemana = 7) And (diasAtraso < 2 And intSemana = 1) Or (diasAtraso < 4 And bFeriado) Then
						'nao faz nada
					Else
						If diasAtraso > 0 And strCobrado = "N" And vlrNota > 0 And (vlrMulta <> 0 Or vlrJuros <> 0 Or vlrCM <> 0) Then
							strsql = "INSERT INTO multajuros (codigo, zona, livro, conta, numnf, mesano, diasatraso, vlrmulta, vlrjuros, vlrcm, cobrado, dat_processo, mesano_fatur "
							If alngUnidId > 0 And alngConsId > 0 Then
								strsql = strsql & ", cons_id , unid_id "
							End If
							strsql = strsql & ") VALUES(0"
							strsql = strsql & ", '" & rsFatura.Fields("Zona").Value & "'"
							strsql = strsql & ", '" & rsFatura.Fields("Livro").Value & "'"
							strsql = strsql & ", '" & rsFatura.Fields("Conta").Value & "'"
							strsql = strsql & ",  " & rsFatura.Fields("numNf").Value & " "
							strsql = strsql & ", '" & rsFatura.Fields("mesano").Value & "'"
							strsql = strsql & ",  " & diasAtraso & " "
							strsql = strsql & ",  " & Replace(CStr(Arredondar(vlrMulta, 2)), ",", ".") & " "
							strsql = strsql & ",  " & Replace(CStr(Arredondar(vlrJuros, 2)), ",", ".") & " "
							strsql = strsql & ",  " & Replace(CStr(Arredondar(vlrCM, 2)), ",", ".") & " "
							strsql = strsql & ", 'N' "
							strsql = strsql & ", current_date "
							strsql = strsql & ", '" & mesano & "'"
							If alngUnidId > 0 And alngConsId > 0 Then
								strsql = strsql & ",  " & alngConsId & ", " & alngUnidId
							End If
							strsql = strsql & ");"
							Call Executar(strsql)
						End If
					End If
				End If
				If rsMultaJuro.State = 1 Then Call rsMultaJuro.Close()
				rsFatura.MoveNext()
			End While
		End If
		If rsFatura.State = 1 Then Call rsFatura.Close()
	End Sub
	
	Public Function IndiceCMDia(ByVal aintMes As Short, ByVal aintAno As Short) As Double
		Dim lstrSql As String
		Dim ldblAux As Double
		Dim lintDiasMes As Short
		Dim ldteAux As Date
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		ldblAux = 0
		ldteAux = CDate(UltimoDiaMes(aintMes, aintAno) & "/" & aintMes & "/" & aintAno)
		lstrSql = "SELECT * FROM indicecm WHERE mesano <= '" & VB6.Format(ldteAux, "yyyy-MM-dd") & "' ORDER BY mesano DESC LIMIT 0, 1; "
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					ldblAux = CDbl(IIf(IsDbNull(.Fields("vlrindice").value), 0, .Fields("vlrindice").value))
					ldblAux = Arredondar((ldblAux / 100) / VB.Day(ldteAux), 12)
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		IndiceCMDia = ldblAux
	End Function
	
	'função para truncar números
	Public Function Truncate(ByVal adblValor As Double, Optional ByVal aintCasas As Short = 0) As Double
		Dim ldblFator As Double
		Dim ldblTemp As Double
		Dim ldblRet As Double
		Dim lstrAux As String
		Dim lstrFormato As String
		
		ldblFator = 10 ^ aintCasas
		ldblTemp = adblValor * ldblFator
		lstrAux = Replace(CStr(ldblTemp), ",", ".")
		If InStr(1, lstrAux, ".") > 0 Then
			lstrAux = Left(lstrAux, InStr(1, lstrAux, ".") - 1)
		ElseIf InStr(1, lstrAux, ",") > 0 Then 
			lstrAux = Left(lstrAux, InStr(1, lstrAux, ",") - 1)
		End If
		ldblRet = Val(lstrAux) / ldblFator
		'ldblRet = ldblTemp / ldblFator
		Truncate = ldblRet
		'  ldblRet = Conversion.Int(ldblTemp)
		'  Truncate = Int(ldblTemp) / ldblFator
	End Function
	
	Public Function Arredondar(ByRef Num As Double, Optional ByRef casas As Short = 0) As Double
		Arredondar = CDbl(FormatNumber(Num, casas))
	End Function
	
	Public Function PreparaCampo(ByRef Campo As String, ByRef tipo_campo As Short, ByRef comp As Short, ByRef Caracter As String) As String
		Campo = Trim(Campo)
		
		'TIPO NUMERICO
		If tipo_campo = 0 Then
			Campo = Replace(Campo, ",", "")
			Campo = Replace(Campo, ".", "")
			
			If Len(Campo) > comp Then
				PreparaCampo = Left(Campo, comp)
			Else
				PreparaCampo = New String(Caracter, comp - Len(Campo)) & Campo
			End If
		End If
		
		'TIPO ALFANUMÉRICO
		If tipo_campo = 1 Then
			If Len(Campo) > comp Then
				PreparaCampo = Left(Campo, comp)
			Else
				PreparaCampo = Campo & New String(Caracter, comp - Len(Campo))
			End If
		End If
	End Function
	
	Public Sub AtualizaRamal(ByVal alngIdRamal As Integer, ByVal alngRamalSituacao As Integer)
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		
		If alngRamalSituacao = 5 Then
			'ramal
			'3 - Retirado
			lstrSql = ""
			lstrSql = lstrSql & "UPDATE ramal "
			lstrSql = lstrSql & "   SET idsituacao = " & alngRamalSituacao & " "
			lstrSql = lstrSql & " WHERE id = " & alngIdRamal & " "
			Call Executar(lstrSql)
		End If
	End Sub
	
	Public Sub AtualizaMedidor(ByVal alngIdMedidor As Integer, ByVal alngMedidorSituacao As Integer)
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		
		If alngMedidorSituacao = 1 Or alngMedidorSituacao = 6 Or alngMedidorSituacao = 7 Then
			'medidor
			'7 - Liberado
			'1 - Instalado
			'6 - Sucata
			lstrSql = ""
			lstrSql = lstrSql & "UPDATE medidores "
			lstrSql = lstrSql & "   SET idsituacao = " & alngMedidorSituacao & " "
			lstrSql = lstrSql & " WHERE id = " & alngIdMedidor & " "
			Call Executar(lstrSql)
		End If
	End Sub
	
	Public Sub AtualizaMedidorUnidadeConsumidora(ByVal alngIdMedidor As Integer, ByVal alngIdUnidadeConsumidora As Integer, ByVal alngUnidadeConsumidoraSituacao As Integer, ByVal astrProtocolo As String, ByVal alngSequencia As Integer, ByVal astrObservacao As String)
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		'medidor_unidade_consumidora
		'Inicia o processo da UC vs Medidor com ele Instalado na UC
		'1 - Instalado
		'
		'Após isso o Medidor da UC pode ser Desligado e com futuramente Religado ou Ir para Manutenção e quando voltar ser Religado
		'4 - Desligado
		'2 - Religado
		'8 - Manutenção
		'
		'
		'5 - Desativado
		'1 - Instalado
		'
		'3 - Retirado
		'6 - Sucata
		lstrSql = ""
		lstrSql = lstrSql & "INSERT INTO medidores_unidade_consumidora "
		lstrSql = lstrSql & "   SET idsituacao = " & alngUnidadeConsumidoraSituacao & ", "
		lstrSql = lstrSql & "       idmedidor = " & alngIdMedidor & ", "
		lstrSql = lstrSql & "       idunidade_consumidora = " & alngIdUnidadeConsumidora & ", "
		lstrSql = lstrSql & "       lancamento = '" & VB6.Format(BuscaDataBD, "yyyy-MM-dd hh:mm:ss") & "', "
		lstrSql = lstrSql & "       situacao = 'Ativo', "
		lstrSql = lstrSql & "       idusuarios = " & glngUsuario_Id & ", "
		lstrSql = lstrSql & "       os_id = " & alngSequencia & ", "
		lstrSql = lstrSql & "       os_protocolo = '" & astrProtocolo & "', "
		lstrSql = lstrSql & "       observacao = '" & Replace(Trim(astrObservacao), "'", "\'") & "' "
		Call Executar(lstrSql, True)
	End Sub
	
	Public Sub AtualizaRamalUnidadeConsumidora(ByVal alngIdRamal As Integer, ByVal alngIdUnidadeConsumidora As Integer, ByVal alngUnidadeConsumidoraSituacao As Integer, ByVal alngIdTipoPadraoMedicao As Integer, ByVal astrProtocolo As String, ByVal alngSequencia As Integer, ByVal astrObservacao As String)
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrSql = ""
		lstrSql = lstrSql & "INSERT INTO ramal_unidade_consumidora "
		lstrSql = lstrSql & "   SET idsituacao = " & alngUnidadeConsumidoraSituacao & ", "
		lstrSql = lstrSql & "       idramal = " & alngIdRamal & ", "
		lstrSql = lstrSql & "       idunidade_consumidora = " & alngIdUnidadeConsumidora & ", "
		lstrSql = lstrSql & "       idtipo_padrao_medicao = " & alngIdTipoPadraoMedicao & ", "
		lstrSql = lstrSql & "       lancamento = '" & VB6.Format(BuscaDataBD, "yyyy-MM-dd hh:mm:ss") & "', "
		lstrSql = lstrSql & "       situacao = 'Ativo', "
		lstrSql = lstrSql & "       idusuarios = " & glngUsuario_Id & ", "
		lstrSql = lstrSql & "       os_id = " & alngSequencia & ", "
		lstrSql = lstrSql & "       os_protocolo = '" & astrProtocolo & "', "
		lstrSql = lstrSql & "       observacao = '" & Replace(Trim(astrObservacao), "'", "\'") & "' "
		Call Executar(lstrSql)
	End Sub
	
	Public Sub AtualizaHistoricoFatura(ByVal adblNumNf As Double, ByVal astrMesAno As String, ByVal alngMesAno As Integer, ByVal astrTipo As String, ByVal astrSolicitante As String, ByVal astrDescricao As String)
		Dim lstrSql As String
		Dim ldteBas As Date
		ldteBas = BuscaHoraBD
		lstrSql = ""
		lstrSql = lstrSql & "INSERT INTO `nf_historico` (`numnf`, `mesano`, `mesano_ref`, `lancamento`, `tipo`, `solicitante`, `descricao`, `situacao`, `idusuarios`) VALUES("
		lstrSql = lstrSql & " " & adblNumNf & ", "
		lstrSql = lstrSql & "'" & astrMesAno & "', "
		lstrSql = lstrSql & " " & alngMesAno & ", "
		lstrSql = lstrSql & "'" & VB6.Format(ldteBas, "yyyy-MM-dd HH:NN:SS") & "', "
		lstrSql = lstrSql & "'" & astrTipo & "', "
		lstrSql = lstrSql & "'" & astrSolicitante & "', "
		lstrSql = lstrSql & "'" & astrDescricao & "', "
		lstrSql = lstrSql & "'Ativo', "
		lstrSql = lstrSql & " " & glngUsuario_Id & ") "
		Call Executar(lstrSql)
		lstrSql = ""
		lstrSql = lstrSql & "UPDATE `nf` SET "
		lstrSql = lstrSql & "       `motivosegvia`  = '" & astrDescricao & "', "
		lstrSql = lstrSql & "       `usuariosegvia` = '" & gstrUsuario_Nome & "', "
		lstrSql = lstrSql & "       `datasegvia`    = '" & VB6.Format(ldteBas, "yyyy-MM-dd") & "' "
		lstrSql = lstrSql & " WHERE `numnf`  = " & adblNumNf
		lstrSql = lstrSql & "   AND `mesano` = '" & astrMesAno & "' "
		Call Executar(lstrSql)
	End Sub
	
	Public Sub AtualizaHistoricoUnidade(ByVal alngUnidId As Integer, ByVal astrGrupo As String, ByVal astrMensagem As String)
		'Versão: 001 Desenvolvedor: Ricardo Inacio Data: 10/07/2008 Descrição: Rotina para atualizar o hitorico da unidade consumidora
		Dim lstrSql As String
		
		'----- Atualiza histórico da unidade consumidora ---------------------------------------------------------
		lstrSql = "UPDATE unid" & LCase(astrGrupo) & " " & "   SET historico = CONCAT(IFNULL(historico, ''), IF(historico IS NULL OR LENGTH(TRIM(historico)) = 0, '', CONVERT(""\r\n"" USING latin1)), CONVERT(""" & astrMensagem & """ USING latin1)) " & " WHERE unid_id = " & alngUnidId & " "
		Call Executar(lstrSql)
		'---------------------------------------------------------------------------------------------------------
	End Sub
	
	Public Sub AtualizaSituacaoUnidade(ByVal alngUnidId As Integer, ByVal astrGrupo As String, ByVal astrSituacao As String, ByVal adteAuxiliar As Date, Optional ByVal astrTipo As String = "OS", Optional ByVal astrRetiraMedidor As String = "N")
		Dim lstrSql As String
		'----- Atualiza situacao da unidade consumidora ---------------------------------------------------------
		lstrSql = ""
		lstrSql = lstrSql & "UPDATE unid" & LCase(astrGrupo) & " "
		lstrSql = lstrSql & "   SET situacao = """ & astrSituacao & """ "
		If astrTipo = "NO" Then
			lstrSql = lstrSql & ", data_ligacao = """ & VB6.Format(adteAuxiliar, "yyyy-MM-dd") & """ "
			lstrSql = lstrSql & ", dtainstmedidor  = """ & VB6.Format(adteAuxiliar, "yyyy-MM-dd") & """ "
			lstrSql = lstrSql & ", data_entrada  = """ & VB6.Format(adteAuxiliar, "yyyy-MM-dd") & """ "
		Else
			If astrSituacao = "L" Then
				lstrSql = lstrSql & ", data_religacao = """ & VB6.Format(adteAuxiliar, "yyyy-MM-dd") & """ "
				lstrSql = lstrSql & ", data_corte = NULL "
			ElseIf (astrSituacao = "D" Or astrSituacao = "I") Then 
				lstrSql = lstrSql & ", data_desligamento = """ & VB6.Format(adteAuxiliar, "yyyy-MM-dd") & """ "
				If astrRetiraMedidor = "S" Then
					If UCase(astrGrupo) = "B" Then
						lstrSql = lstrSql & ", num = ''"
					ElseIf UCase(astrGrupo) = "A" Then 
						lstrSql = lstrSql & ", eletr = ''"
					End If
				End If
			ElseIf astrSituacao = "C" Then 
				lstrSql = lstrSql & ", data_corte = """ & VB6.Format(adteAuxiliar, "yyyy-MM-dd") & """ "
			End If
		End If
		lstrSql = lstrSql & " WHERE unid_id = " & alngUnidId & " "
		Call Executar(lstrSql)
	End Sub
	
	Public Sub AtualizaSituacaoUnidadeLC(ByVal alngUnidId As Integer, ByVal astrGrupo As String, ByVal astrSituacao As String, ByVal adteAuxiliar As Date, Optional ByVal astrTipo As String = "OS", Optional ByVal astrRetiraMedidor As String = "N")
		Dim lstrSql As String
		
		'----- Atualiza situacao da unidade consumidora ---------------------------------------------------------
		lstrSql = ""
		lstrSql = lstrSql & "UPDATE " & gstrBDCLinkCenter & ".`uc` "
		lstrSql = lstrSql & "   SET situacao = 'C' "
		lstrSql = lstrSql & ", data_corte = '" & VB6.Format(adteAuxiliar, "yyyy-MM-dd") & "' "
		lstrSql = lstrSql & " WHERE unid_id_fatwin = " & alngUnidId & " "
		lstrSql = lstrSql & "   AND grupo = '" & astrGrupo & "' "
		Call Executar(lstrSql)
	End Sub
	
	Public Sub AtualizaSituacaoRamal(ByVal alngUnidId As Integer, ByVal astrGrupo As String, ByVal adteAuxiliar As Date, ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal astrSituacao As String, ByVal astrProtocolo As String, ByVal alngSequencia As Integer)
		Dim lstrSql As String
		
		'----- Atualiza situacao do ramal unidade consumidora ---------------------------------------------------------
		'  lstrSql = ""
		'  lstrSql = lstrSql & "INSERT INTO histramal "
		'  lstrSql = lstrSql & "   SET movto    = """ & Format(adteAuxiliar, "yyyy-MM-dd hh:mm:ss") & """, "
		'  lstrSql = lstrSql & "       grupo    = """ & astrGrupo & """, "
		'  lstrSql = lstrSql & "       unid_id  =   " & alngUnidId & ", "
		'  lstrSql = lstrSql & "       zona     = """ & astrZona & """, "
		'  lstrSql = lstrSql & "       livro    = """ & astrLivro & """, "
		'  lstrSql = lstrSql & "       conta    = """ & astrConta & """, "
		'  lstrSql = lstrSql & "       situacao = """ & astrSituacao & """, "
		'  lstrSql = lstrSql & "       codsolserv = " & alngSequencia & ", "
		'  lstrSql = lstrSql & "       protocolo  = """ & astrProtocolo & """ "
		'  Call Executar(lstrSql)
	End Sub
	
	Public Sub toClip(ByRef Texto As String)
		My.Computer.Clipboard.Clear()
		My.Computer.Clipboard.SetText(Texto)
	End Sub
	
	Public Function toNumeric(ByRef Texto As String) As Double
		Dim aux As String
		Dim pos As Short
		If Len(Texto) > 0 Then
			
			pos = 1
			aux = Texto
			
			While pos <= Len(aux)
				If Not IsNumeric(Mid(aux, pos, 1)) Then
					aux = Replace(aux, Mid(aux, pos, 1), "")
					pos = pos - 1
				End If
				
				pos = pos + 1
			End While
		End If
		
		toNumeric = Val(aux)
	End Function
	
	Public Function BuscaVlrItem(ByVal astrTexto As String, ByVal astrBusca As String) As Double
		Dim intP1 As Short
		Dim intP2 As Short
		Dim intP3 As Short
		Dim intP4 As Short
		Dim intTe As Short
		Dim strAux As String
		Dim strCod As String
		Dim dblValor As Double
		
		intP1 = 1
		intP1 = InStr(intP1, astrTexto, astrBusca)
		
		If intP1 > 0 Then
			While intP1 <= Len(astrTexto)
				intP2 = InStr(intP1, astrTexto, ";")
				strAux = Trim(Mid(astrTexto, intP1, intP2 - intP1))
				intP3 = InStr(1, strAux, "?")
				intP4 = InStr(1, strAux, "$")
				If intP3 > 0 Then
					strCod = Left(strAux, intP3 - 1)
					
					If Left(strCod, Len(astrBusca)) = astrBusca Then
						If intP4 > 0 Then
							dblValor = CDbl(Replace(Mid(strAux, intP3 + 1, (intP4 - 1) - intP3), ".", ","))
						Else
							dblValor = CDbl(Replace(Mid(strAux, intP3 + 1, Len(strAux) - intP3), ".", ","))
						End If
					End If
					If Len(astrBusca) < 11 Then
						If Left(strCod, Len(astrBusca)) = astrBusca Then
							BuscaVlrItem = BuscaVlrItem + dblValor
						End If
					End If
				End If
				intP1 = intP2 + 1
			End While
		End If
	End Function
	
	Public Function BuscaValorItem(ByVal astrTexto As String, ByVal astrBusca As String) As Double
		Dim intP1 As Short
		Dim intP2 As Short
		Dim intP3 As Short
		Dim intP4 As Short
		Dim intTe As Short
		Dim strAux As String
		Dim strCod As String
		Dim dblValor As Double
		Dim ldblRet As Double
		
		intP1 = 1
		intP1 = InStr(intP1, astrTexto, astrBusca)
		ldblRet = 0
		If intP1 > 0 Then
			While intP1 <= Len(astrTexto)
				intP2 = InStr(intP1, astrTexto, ";")
				strAux = Trim(Mid(astrTexto, intP1, intP2 - intP1))
				intP3 = InStr(1, strAux, "?")
				intP4 = InStr(1, strAux, "$")
				If intP3 > 0 Then
					strCod = Left(strAux, intP3 - 1)
					
					If intP4 > 0 Then
						If strCod <> "0302080099" Then
							If (intP3 + 1) = intP4 Then
								dblValor = 0
							Else
								dblValor = CDbl(Replace(Mid(strAux, intP3 + 1, IIf(((intP4 - 1) - intP3) <= 0, 1, (intP4 - 1) - intP3)), ".", ","))
							End If
						End If
					Else
						If strCod <> "0302080099" Then
							If intP3 + 1 > Len(strAux) Then
								dblValor = 0
							Else
								dblValor = CDbl(Replace(Mid(strAux, intP3 + 1, IIf((Len(strAux) - intP3) <= 0, 1, Len(strAux) - intP3)), ".", ","))
							End If
						End If
					End If
					If Left(strCod, Len(astrBusca)) = astrBusca Then
						ldblRet = ldblRet + dblValor
					End If
				End If
				intP1 = intP2 + 1
			End While
		End If
		BuscaValorItem = ldblRet
	End Function
	
	Public Function BuscaRefItem(ByVal astrTexto As String, ByVal astrBusca As String) As String
		Dim intP1 As Short
		Dim intP2 As Short
		Dim intP3 As Short
		Dim intP4 As Short
		Dim strAux As String
		Dim strCod As String
		intP1 = 1
		intP1 = InStr(intP1, astrTexto, astrBusca)
		If intP1 > 0 Then
			While intP1 <= Len(astrTexto)
				intP2 = InStr(intP1, astrTexto, ";")
				strAux = Mid(astrTexto, intP1, intP2 - intP1)
				intP3 = InStr(1, strAux, "?")
				intP4 = InStr(1, strAux, "$")
				strCod = Left(strAux, intP3 - 1)
				If Left(strCod, Len(astrBusca)) = astrBusca Then
					If intP4 > 0 Then
						BuscaRefItem = Mid(strAux, intP4 + 1, (intP2 - 1) - intP3)
					Else
						BuscaRefItem = ""
					End If
				End If
				intP1 = intP2 + 1
			End While
		End If
	End Function
	
	Public Function VerificaDiaUtil(ByVal adteAux As Date) As Boolean
		Dim lblnRet As Boolean
		If WeekDay(adteAux, FirstDayOfWeek.Sunday) = FirstDayOfWeek.Saturday Or WeekDay(adteAux, FirstDayOfWeek.Sunday) = FirstDayOfWeek.Sunday Then
			lblnRet = False
		Else
			lblnRet = (Not VerificaFeriado(adteAux))
		End If
		VerificaDiaUtil = lblnRet
	End Function
	
	Public Function VerificaFeriado(ByVal adteVcto As Date) As Boolean
		Dim lstrSql As String
		Dim lrstFeriado As ADODB.Recordset
		lrstFeriado = New ADODB.Recordset
		lstrSql = "SELECT * FROM `feriados` WHERE `feriados`.`data` = '" & VB6.Format(adteVcto, "yyyy-MM-dd") & "' "
		Call Conectar(lstrSql, lrstFeriado)
		With lrstFeriado
			VerificaFeriado = .RecordCount > 0
			If .State = ADODB.ObjectStateEnum.adStateOpen Then Call .Close()
		End With
		'UPGRADE_NOTE: Object lrstFeriado may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstFeriado = Nothing
	End Function
	
	Public Sub MontaCodBarras(ByVal adblNumNf As Double, ByVal astrMesAno As String, ByVal adblValor As Double, ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByRef astrCodBarras As String, ByRef astrDvCodBarras As String)
		Dim lstrCodEmp As String
		Dim lstrValorNf As String
		Dim lstrZona As String
		Dim lstrLivro As String
		Dim lstrConta As String
		Dim lstrMesAno As String
		Dim lstrNumNota As String
		Dim lstrAux As String
		Dim lstrdigito As String
		Dim lstrCodBarra(4) As String
		Dim lintDvCodBar(4) As Short
		Dim lintConta1 As Short
		Dim lintConta2 As Short
		Dim lintSomaDV As Short
		Dim lintDvNumNf As Short
		Dim lintMultiplicador As Short
		Dim lintTamanho As Short
		
		lstrCodEmp = VB6.Format(LeConfig("EMPRESA_CODBARRA_FEBRABAN"), "0000")
		lstrValorNf = Left(VB6.Format(Trim(CStr(adblValor * 100)), New String("0", 11)), 11)
		lstrNumNota = Left(VB6.Format(Trim(CStr(adblNumNf)), New String("0", 9)), 11)
		
		lstrZona = Left(VB6.Format(Trim(astrZona), New String("0", 3)), 3)
		lstrLivro = Left(VB6.Format(Trim(astrLivro), New String("0", 2)), 2)
		lstrMesAno = Replace(astrMesAno, "/", "")
		
		lstrMesAno = Left(lstrMesAno, 2) & Right(lstrMesAno, 2)
		lstrConta = Left(VB6.Format(Trim(astrConta), New String("0", 7)), 7)
		lstrCodBarra(0) = "836" & lstrValorNf & lstrCodEmp & lstrNumNota & lstrMesAno & lstrZona & lstrLivro & lstrConta
		lintMultiplicador = 1
		For lintConta2 = 0 To 4
			lstrdigito = ""
			lintConta1 = lintConta2 + lintMultiplicador
			lintTamanho = Len(lstrCodBarra(0))
			If lintTamanho = 44 Then
				lstrCodBarra(lintConta2) = Mid(lstrCodBarra(0), lintConta1, 11)
				lintConta1 = 1
				lintTamanho = 11
			End If
			While lintConta1 <= lintTamanho
				If lintConta1 Mod 2 = 0 Then
					lstrdigito = lstrdigito & Mid(lstrCodBarra(lintConta2), lintConta1, 1)
				Else
					lstrdigito = lstrdigito & CDbl(Mid(lstrCodBarra(lintConta2), lintConta1, 1)) * 2
				End If
				lintConta1 = lintConta1 + 1
			End While
			lintSomaDV = 0
			lintConta1 = 1
			While lintConta1 <= Len(lstrdigito)
				lintSomaDV = lintSomaDV + CDbl(Mid(lstrdigito, lintConta1, 1))
				lintConta1 = lintConta1 + 1
			End While
			lintDvCodBar(lintConta2) = lintSomaDV Mod 10
			lintDvCodBar(lintConta2) = 10 - lintDvCodBar(lintConta2)
			If lintDvCodBar(lintConta2) >= 10 Then
				lintDvCodBar(lintConta2) = 0
			End If
			lintMultiplicador = lintMultiplicador + 10
			If lintTamanho = 43 Then
				lstrCodBarra(0) = Mid(lstrCodBarra(0), 1, 3) & lintDvCodBar(lintConta2) & Mid(lstrCodBarra(0), 4)
				lintMultiplicador = 0
			End If
		Next lintConta2
		astrCodBarras = lstrCodBarra(0)
		astrDvCodBarras = lintDvCodBar(1) & lintDvCodBar(2) & lintDvCodBar(3) & lintDvCodBar(4)
	End Sub
	
	Public Function BuscaDataBD() As Date
		Dim lstrSql As String
		Dim ldteAux As Date
		Dim lrstData As ADODB.Recordset
		lrstData = New ADODB.Recordset
		lstrSql = "SELECT CONVERT(CURRENT_DATE USING latin1) data_bd , CONVERT(CURRENT_TIME USING latin1) hora_bd"
		Call Conectar(lstrSql, lrstData)
		With lrstData
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					ldteAux = CDate(VB6.Format(IIf(IsDbNull(.Fields("data_bd").Value), Today, .Fields("data_bd").Value), "DD/MM/YYYY"))
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					ldteAux = CDate(VB6.Format(ldteAux & " " & VB6.Format(IIf(IsDbNull(.Fields("hora_bd").Value), Now, .Fields("hora_bd").Value), "HH:MM:SS"), "DD/MM/YYYY HH:MM:SS"))
				Else
					ldteAux = Now
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstData may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstData = Nothing
		BuscaDataBD = ldteAux
	End Function
	
	Public Function BuscaHoraBD() As Date
		Dim lstrSql As String
		Dim ldteAux As Date
		Dim lrstData As ADODB.Recordset
		lrstData = New ADODB.Recordset
		lstrSql = "SELECT CONVERT(DATE_FORMAT(localtime(),""%Y-%m-%d %T"") USING latin1) data_bd "
		Call Conectar(lstrSql, lrstData)
		With lrstData
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					ldteAux = CDate(VB6.Format(IIf(IsDbNull(.Fields("data_bd").value), Now, .Fields("data_bd").value), "DD/MM/YYYY HH:MM:SS"))
				Else
					ldteAux = Today
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstData may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstData = Nothing
		BuscaHoraBD = ldteAux
	End Function
	
	Public Sub CarregaTabelaComboBox(ByRef acmbAux As System.Windows.Forms.ComboBox, ByVal astrTabela As String, ByVal astrCampoDescr As String, Optional ByVal astrCampoCod As String = "", Optional ByVal astrOrdena As String = "", Optional ByVal astrTodos As String = "", Optional ByVal aintLista As Short = 0, Optional ByVal astrCodicao As String = "", Optional ByRef ablnBarraProgresso As Boolean = False, Optional ByRef aPgbAux As System.Windows.Forms.ProgressBar = Nothing, Optional ByRef alblPerc As System.Windows.Forms.Label = Nothing, Optional ByRef alblInfo As System.Windows.Forms.Label = Nothing)
		'Sub - Rotina que carrega os dados de uma tabela na combo box
		'Obrigatórios
		'acmbAux = objeto combobox
		'astrTabela = Nome da tabela no banco de dados
		'astrCampoDescr = Nome do campo da tabela que aparecerá na lista da combobox
		'Opicionais
		'astrCampoCod = Código que irá para o itemdata da combobox
		'astrOrdena = Ordenação da tabela mandar se vai ser ASC ou DESC
		'aintTodos = Se vai aparecer no lisindex = 0 a opção TODOS
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		Call acmbAux.Items.Clear()
		lstrSql = lstrSql & "SELECT  " & astrCampoDescr & IIf(Len(Trim(astrCampoCod)) > 0, "," & astrCampoCod, "")
		lstrSql = lstrSql & "  FROM " & astrTabela
		If Len(Trim(astrCodicao)) > 0 Then
			lstrSql = lstrSql & " WHERE " & astrCodicao
		End If
		If Len(Trim(astrOrdena)) > 0 Then
			lstrSql = lstrSql & " ORDER BY " & astrOrdena
		End If
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .RecordCount > 0 Then
				If ablnBarraProgresso Then
					Call BarraProgresso(aPgbAux, alblPerc, alblInfo, 0, .RecordCount)
				End If
				System.Windows.Forms.Application.DoEvents()
				If Len(Trim(astrTodos)) > 0 Then
					Call acmbAux.Items.Add(astrTodos)
					VB6.SetItemData(acmbAux, acmbAux.Items.Count - 1, 0)
				End If
				While Not .EOF
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					Call acmbAux.Items.Add(IIf(IsDbNull(.Fields(0).value), "nenhum", .Fields(0).value))
					If Len(Trim(astrCampoCod)) > 0 Then
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						VB6.SetItemData(acmbAux, acmbAux.Items.Count - 1, IIf(IsDbNull(.Fields(1).value), 0, .Fields(1).value))
					End If
					Call .MoveNext()
					If ablnBarraProgresso Then
						Call BarraProgresso(aPgbAux, alblPerc, alblInfo, 1)
					End If
				End While
			Else
				Call acmbAux.Items.Add("nenhum")
			End If
			If .State = 1 Then Call .Close()
		End With
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		If aintLista = 1 Then
			acmbAux.SelectedIndex = -1
		Else
			If acmbAux.Items.Count > 0 Then
				acmbAux.SelectedIndex = 0
			End If
		End If
		System.Windows.Forms.Application.DoEvents()
	End Sub
	
	Public Function trocaZonaLivro(ByRef astrZona As String, ByRef astrLivro As String) As Object
		Dim strZona As String
		Dim strLivro As String
		
		strZona = astrZona
		strLivro = astrLivro
		'zona = 002
		If strZona = "002" And strLivro = "01" Then
			strZona = "001"
			strLivro = "06"
		ElseIf strZona = "002" And strLivro = "02" Then 
			strZona = "001"
			strLivro = "07"
		ElseIf strZona = "002" And strLivro = "03" Then 
			strZona = "001"
			strLivro = "08"
		ElseIf strZona = "002" And strLivro = "04" Then 
			strZona = "001"
			strLivro = "09"
		ElseIf strZona = "002" And strLivro = "05" Then 
			strZona = "001"
			strLivro = "10"
		ElseIf strZona = "003" And strLivro = "01" Then 
			strZona = "001"
			strLivro = "11"
		ElseIf strZona = "003" And strLivro = "02" Then 
			strZona = "001"
			strLivro = "12"
		ElseIf strZona = "003" And strLivro = "03" Then 
			strZona = "001"
			strLivro = "13"
		ElseIf strZona = "003" And strLivro = "04" Then 
			strZona = "001"
			strLivro = "14"
		ElseIf strZona = "003" And strLivro = "05" Then 
			strZona = "001"
			strLivro = "15"
		ElseIf strZona = "003" And strLivro = "06" Then 
			strZona = "001"
			strLivro = "16"
		ElseIf strZona = "004" And strLivro = "01" Then 
			strZona = "001"
			strLivro = "17"
		ElseIf strZona = "004" And strLivro = "02" Then 
			strZona = "001"
			strLivro = "18"
			'Grupo A
		ElseIf strZona = "150" And strLivro = "01" Then 
			strZona = "001"
			strLivro = "19"
		ElseIf strZona = "100" And strLivro = "01" Then 
			strZona = "001"
			strLivro = "20"
		End If
		astrZona = strZona
		astrLivro = strLivro
	End Function
	
	'Ela serve para atualizar os consumos nas telas de arrecadação, toda vez que atualiza a NF, atualiza-se a Consumos também, e para isso chama-se esta função.
	Public Function AtualizaConsumos(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal astrMesAno As String, ByVal adblNumNf As Double, Optional ByVal alngUnidId As Integer = 0, Optional ByVal alngConsId As Integer = 0) As Object
		Dim lstrSql As String
		Dim lintConta As Short
		Dim lintAux As Short
		Dim lrstConsulta As ADODB.Recordset
		
		lrstConsulta = New ADODB.Recordset
		
		lintAux = 12
		For lintConta = 11 To 0 Step -1
			lstrSql = "SELECT * " & "  FROM `consumos` " & " WHERE mesano" & lintConta & " = """ & astrMesAno & """ " & "   AND zona = """ & astrZona & """ " & "   AND livro = """ & astrLivro & """ " & "   AND conta = """ & astrConta & """ "
			Call Conectar(lstrSql, lrstConsulta)
			With lrstConsulta
				If .RecordCount > 0 Then
					lintAux = lintConta
					lintConta = 0
				End If
				If .State = 1 Then Call .Close()
			End With
		Next lintConta
		If lintAux < 12 Then
			lstrSql = "UPDATE `consumos`, nf SET " & "       consumos.datapag" & lintAux & " = nf.datapag, " & "       consumos.valor" & lintAux & " = if(nf.valorliq > 0, nf.valorliq, nf.valortot) " & " WHERE consumos.mesano" & lintAux & " = nf.mesano " & "   AND consumos.zona = """ & astrZona & """ " & "   AND consumos.livro = """ & astrLivro & """ " & "   AND consumos.conta = """ & astrConta & """ " & "   AND consumos.zona = nf.zona " & "   AND consumos.livro = nf.livro " & "   AND consumos.conta = nf.conta " & "   AND nf.numnf = " & adblNumNf
			Call Executar(lstrSql)
		End If
	End Function
	
	Public Sub CarregaTipoSituacao(ByRef acmbAuxiliar As System.Windows.Forms.ComboBox)
		'Versão: 001 Desenvolvedor: Ricardo Inacio Data: 06/11/2008
		'Sub-Rotina para popular os tipos da situação da unidade consumidora
		'UPGRADE_WARNING: Lower bound of array lstrSituacao was changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="0F1C9BE1-AF9D-476E-83B1-17D43BECFF20"'
		Dim lstrSituacao(2) As String
		'UPGRADE_WARNING: Lower bound of array lintPosicoes was changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="0F1C9BE1-AF9D-476E-83B1-17D43BECFF20"'
		Dim lintPosicoes(2) As Short
		
		Call acmbAuxiliar.Items.Clear()
		lintPosicoes(1) = 1
		lstrSituacao(1) = UCase(LeConfig("TIPO_SITUACAO"))
		If Trim(lstrSituacao(1)) <> "-1" Then
			While lintPosicoes(1) <= Len(lstrSituacao(1))
				lintPosicoes(2) = InStr(lintPosicoes(1), lstrSituacao(1), ";")
				lstrSituacao(2) = Mid(lstrSituacao(1), lintPosicoes(1), lintPosicoes(2) - lintPosicoes(1))
				Call acmbAuxiliar.Items.Add(lstrSituacao(2))
				lintPosicoes(1) = lintPosicoes(2) + 1
			End While
		Else
			If CriaParConfig("TIPO_SITUACAO", "Ligado;Desligado;Inativado;Cortado;Não Ligado;", False, "Situação da unidade consumidora(Ligado,Desligado,Inativo,Cortado)") = -1 Then
				Call GravaConfig("TIPO_SITUACAO", "Ligado;Desligado;Inativo;Cortado;Não Ligado;")
			End If
		End If
	End Sub
	
	Public Function RetiraAcentuacao(ByVal astrTexto As String) As String
		Dim lintPos As Short
		Dim lstrComAcento As String
		Dim lstrSemAcento As String
		Dim lintConta As Short
		
		lstrComAcento = "ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜàáâãäåçèéêëìíîïòóôõöùúûü"
		lstrSemAcento = "AAAAAACEEEEIIIIOOOOOUUUUaaaaaaceeeeiiiiooooouuuu"
		For lintConta = 1 To Len(astrTexto)
			lintPos = InStr(1, lstrComAcento, Mid(astrTexto, lintConta, 1))
			If lintPos > 0 Then
				Mid(astrTexto, lintConta, 1) = Mid(lstrSemAcento, lintPos, 1)
			End If
		Next lintConta
		RetiraAcentuacao = astrTexto
	End Function
	
	Public Function BuscaCodEnd(ByVal astrNomeCidade As String) As String
		'Função que retorna o código do IBGE de acordo com o nome da cidade passado no argumento
		Dim lstrRet As String
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrRet = ""
		lstrSql = ""
		lstrSql = lstrSql & "SELECT * "
		lstrSql = lstrSql & "  FROM " & gstrDataBase & ".`munic` "
		lstrSql = lstrSql & " WHERE `nome` = '" & Replace(astrNomeCidade, "'", "\'") & "' "
		lstrSql = lstrSql & " LIMIT 0, 1 "
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrRet = Trim(IIf(IsDbNull(.Fields("cod").value), "000001", .Fields("cod").value))
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		BuscaCodEnd = lstrRet
	End Function
	
	Public Function BuscaConsumo(ByVal astrGrupo As String, ByVal alngUnidId As Integer, ByVal astrMesAno As String, Optional ByVal alngConsId As Integer = 0, Optional ByVal aintTipo As Short = 0, Optional ByRef astrCodClas As String = "") As Double
		Dim lstrIte As String
		Dim lstrGTa As String
		Dim ldblAux As Double
		Dim ldblRet As Double
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrSql = ""
		lstrSql = lstrSql & "SELECT * "
		lstrSql = lstrSql & "  FROM `nf` "
		lstrSql = lstrSql & " WHERE `unid_id` = " & alngUnidId & " "
		lstrSql = lstrSql & "   AND `grupo` = '" & Left(astrGrupo, 1) & "' "
		If alngConsId > 0 Then
			lstrSql = lstrSql & "   AND `cons_id` = " & alngConsId & " "
		End If
		lstrSql = lstrSql & "   AND `mesano`  = '" & astrMesAno & "' "
		lstrSql = lstrSql & " ORDER BY mesano_ref DESC LIMIT 0, 1"
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					If Left(astrGrupo, 1) = "A" Then
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						astrCodClas = Trim(IIf(IsDbNull(.Fields("ta").value), "01A400", .Fields("ta").value))
					Else
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						astrCodClas = Trim(IIf(IsDbNull(.Fields("codclas").value), "", .Fields("codclas").value))
					End If
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrIte = Trim(IIf(IsDbNull(.Fields("itensserv").value), "0", .Fields("itensserv").value))
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrGTa = Mid(Trim(IIf(IsDbNull(.Fields("ta").value), "01B100", .Fields("ta").value)), 3, 2)
					If aintTipo = 1 Then 'Consumo
						ldblRet = BuscaVlrItem(lstrIte, "030201009") + BuscaVlrItem(lstrIte, "0302010009") + BuscaVlrItem(lstrIte, "0302010010") + BuscaVlrItem(lstrIte, "0302010011")
					ElseIf aintTipo = 0 Then  'Consumo
						ldblRet = BuscaVlrItem(lstrIte, "030201008") + BuscaVlrItem(lstrIte, "0302010008") + BuscaVlrItem(lstrIte, "0302010010") + BuscaVlrItem(lstrIte, "0302010011")
					ElseIf aintTipo = 2 Then  'Demanda Máxima
						If lstrGTa = "AA" Or lstrGTa = "AV" Or lstrGTa = "AL" Or lstrGTa = "AX" Then
							ldblAux = BuscaVlrItem(lstrIte, "0302010019")
							ldblRet = BuscaVlrItem(lstrIte, "0302010023")
							If ldblAux > ldblRet Then
								ldblRet = ldblAux
							End If
						Else
							ldblRet = BuscaVlrItem(lstrIte, "0302010015")
						End If
					End If
				Else
					ldblRet = 0
				End If
				Call .Close()
			End If
		End With
		BuscaConsumo = ldblRet
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
	End Function
	
	Public Function RetornaNomeBanco(ByVal alngBcoId As Integer) As String
		Dim lstrRet As String
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrSql = ""
		lstrSql = lstrSql & "SELECT * "
		lstrSql = lstrSql & "  FROM `bancos` "
		lstrSql = lstrSql & " WHERE `ban_id` = " & alngBcoId & " "
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrRet = Trim(IIf(IsDbNull(.Fields("nmbco").value), "", .Fields("nmbco").value))
				Else
					lstrRet = ""
				End If
				Call .Close()
			End If
		End With
		RetornaNomeBanco = lstrRet
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
	End Function
	
	Public Function RetornaAgrupamentoFatura(ByVal astrAgrupaZona As String, ByVal astrAgrupaLivro As String, ByVal astrAgrupaConta As String) As String
		Dim lstrRet As String
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrSql = ""
		lstrSql = lstrSql & "SELECT "
		lstrSql = lstrSql & "       `unidb`.`zona`, "
		lstrSql = lstrSql & "       `unidb`.`livro`, "
		lstrSql = lstrSql & "       `unidb`.`conta`, "
		lstrSql = lstrSql & "       `unidb`.`rota` "
		lstrSql = lstrSql & "  FROM `unidb` "
		lstrSql = lstrSql & " WHERE `unidb`.`zona`  = '" & astrAgrupaZona & "' "
		lstrSql = lstrSql & "   AND `unidb`.`livro` = '" & astrAgrupaLivro & "' "
		lstrSql = lstrSql & "   AND `unidb`.`conta` = '" & astrAgrupaConta & "' "
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrRet = Trim(IIf(IsDbNull(.Fields("rota").value), "", .Fields("rota").value))
				End If
				Call .Close()
			End If
		End With
		RetornaAgrupamentoFatura = lstrRet
	End Function
	
	Public Function BuscaIbge(Optional ByVal alngCidId As Integer = 0, Optional ByVal astrCodEnd As String = "", Optional ByVal astrNomeCidade As String = "") As String
		'Função que retorna o código do IBGE de acordo com o nome da cidade passado no argumento
		Dim lstrRet As String
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrRet = ""
		lstrSql = ""
		lstrSql = lstrSql & "SELECT * "
		lstrSql = lstrSql & "  FROM `munic` "
		lstrSql = lstrSql & " WHERE 1 = 1 "
		If alngCidId > 0 Then
			lstrSql = lstrSql & "   AND `codnum` = " & alngCidId & " "
		End If
		If IsNumeric(Trim(astrCodEnd)) Then
			lstrSql = lstrSql & "   AND cod = '" & Left(astrCodEnd, 6) & "' "
		End If
		If Trim(astrNomeCidade) <> "" Then
			lstrSql = lstrSql & "   AND `nome` = '" & Replace(astrNomeCidade, "'", "\'") & "' "
		End If
		lstrSql = lstrSql & " LIMIT 0, 1 "
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					lstrRet = Trim(IIf(IsDbNull(.Fields("ibge").value), "", .Fields("ibge").value))
				Else
					lstrRet = ""
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		BuscaIbge = lstrRet
	End Function
	
	Public Sub DefineErros()
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(3). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(3) = "Retorno sem GoSub"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(5). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(5) = "Chamada de procedimento inválida ou argumento inválido"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(6). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(6) = "Estouro de memória"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(7). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(7) = "Sem memória"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(9). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(9) = "Subscrito fora do intervalo"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(10). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(10) = "Esta matriz é fixa ou está temporariamente bloqueada"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(11). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(11) = "Divisão por zero"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(13). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(13) = "Tipo incompatível"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(14). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(14) = "Texto fora do espaço permitido"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(16). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(16) = "Expressão demasiado complexa"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(17). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(17) = "Não é possível executar operação solicitada"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(18). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(18) = "Interrompido pelo usuário"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(20). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(20) = "Resume sem erro"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(28). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(28) = "Fora do espaço da pilha"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(35). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(35) = "Rotina ou função não definida"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(47). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(47) = "Demasiadas DLL na aplicação do clientes"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(48). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(48) = "Erro no carregamento da DLL"
		
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(49). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(49) = "Bad DLL calling convention"
		
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(51). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(51) = "Erro interno"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(52). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(52) = "nome do arquivo ou número ruim"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(53). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(53) = "Arquivo não encontrado"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(54). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(54) = "Modo de arquivo incorreto"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(55). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(55) = "Arquivo já esta aberto"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(57). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(57) = "Erro no dispositivo de Entrada e Saída(I/O)"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(58). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(58) = "Arquivo já existe"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(59). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(59) = "Tamanho do registro ruim"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(61). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(61) = "Disco cheio"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(62). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(62) = "Entrada passada no final do arquivo"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(63). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(63) = "Número do registro ruim"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(67). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(67) = "Demasiados arquivos"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(68). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(68) = "Dispositivo indisponível"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(70). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(70) = "Permissão negada"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(71). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(71) = "Disco não esta pronto"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(74). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(74) = "Não é possível renomear com unidade diferente"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(75). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(75) = "Erro no acessao do caminho/arquivo"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(76). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(76) = "Caminho não encontrado"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(91). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(91) = "Não foi definido o objeto variável ou com bloco variável"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(92). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(92) = "Loop sem FOR"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(93). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(93) = "Tipo padrão inválido"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(94). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(94) = "Uso inválido do valor nulo"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(96). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(96) = "Não é possível adicionar eventos a um objeto porque o mesmo já foi disparado para um número determinado de eventos"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(97). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(97) = "Não é possível chamar o objeto de uma função, porque o mesmo não tem sua instância de sua classe definida"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(98). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(98) = "A property or method call cannot include a reference to a private object, either as an argument or as a return value"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(321). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(321) = "Invalid file format"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(322). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(322) = "Can't create necessary temporary file"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(325). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(325) = "Invalid format in resource file"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(380). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(380) = "Invalid property value"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(381). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(381) = "Invalid property array index"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(382). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(382) = "Set not supported at runtime"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(383). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(383) = "Set not supported (read-only property)"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(385). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(385) = "Need property array index"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(387). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(387) = "Set not permitted"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(393). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(393) = "Get not supported at runtime"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(394). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(394) = "Get not supported (write-only property)"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(422). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(422) = "Property not found"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(423). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(423) = "Property or method not found"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(424). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(424) = "Object required"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(429). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(429) = "ActiveX component can't create object"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(430). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(430) = "Class does not support Automation or does not support expected interface"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(432). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(432) = "File name or class name not found during Automation operation"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(438). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(438) = "Object doesn't support this property or method"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(440). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(440) = "Automation error"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(442). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(442) = "Connection to type library or object library for remote process has been lost. Press OK for dialog to remove reference."
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(443). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(443) = "Automation object does not have a default value"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(445). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(445) = "Object doesn't support this action"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(446). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(446) = "Object doesn't support named arguments"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(447). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(447) = "Object doesn't support current locale setting"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(448). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(448) = "Named argument not found"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(449). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(449) = "Argument not optional"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(450). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(450) = "Wrong number of arguments or invalid property assignment"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(451). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(451) = "Property let procedure not defined and property get procedure did not return an object"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(452). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(452) = "Invalid ordinal"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(453). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(453) = "Specified DLL function not found"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(454). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(454) = "Code resource not found"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(455). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(455) = "Code resource lock error"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(457). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(457) = "This key is already associated with an element of this collection"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(458). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(458) = "Variable uses an Automation type not supported in Visual Basic"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(459). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(459) = "Object or class does not support the set of events"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(460). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(460) = "Invalid clipboard format"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(461). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(461) = "Method or data member not found"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(462). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(462) = "The remote server machine does not exist or is unavailable"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(463). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(463) = "Class not registered on local machine"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(481). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(481) = "Invalid picture"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(482). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(482) = "Printer error"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(735). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(735) = "Can't save file to TEMP"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(744). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(744) = "Search text not found"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(746). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(746) = "Replacements too long"
		
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(1000). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(1000) = "Erros internos do Fatwin"
		'UPGRADE_WARNING: Couldn't resolve default property of object gstrErro(1001). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		gstrErro(1001) = "O mês e ano do arquivo de indicadores não é igual ao mês e ano informado!"
	End Sub
	
	Public Sub FaturasNetCriaTabela()
		Dim lstrSql As String
		lstrSql = ""
		lstrSql = lstrSql & "CREATE TABLE IF NOT EXISTS `unidadesnet` ("
		lstrSql = lstrSql & "  `cpf_cnpj` varchar(18) default NULL, "
		lstrSql = lstrSql & "  `zona`  char(3) default NULL, "
		lstrSql = lstrSql & "  `livro` char(2) default NULL, "
		lstrSql = lstrSql & "  `conta` varchar(8) default NULL, "
		lstrSql = lstrSql & "  `grupo` char(1) default NULL, "
		lstrSql = lstrSql & "  `nomecons` varchar(85) default NULL, "
		lstrSql = lstrSql & " PRIMARY KEY  (`cpf_cnpj`, `zona`, `livro`, `conta`, `grupo`), "
		lstrSql = lstrSql & " KEY `keyzona` (`zona`), "
		lstrSql = lstrSql & " KEY `keylivro` (`livro`), "
		lstrSql = lstrSql & " KEY `keyconta` (`conta`), "
		lstrSql = lstrSql & " KEY `keygrupo` (`grupo`), "
		lstrSql = lstrSql & " KEY `keycpf_cnpj` (`cpf_cnpj`) "
		lstrSql = lstrSql & " ) ENGINE=InnoDB DEFAULT CHARSET=latin1 "
		Call Executar(lstrSql)
		lstrSql = ""
		lstrSql = lstrSql & "CREATE TABLE IF NOT EXISTS `faturasnet` ("
		lstrSql = lstrSql & "  `numnf`   double NOT NULL default '0', "
		lstrSql = lstrSql & "  `mesano`  varchar(7) NOT NULL default '', "
		lstrSql = lstrSql & "  `cfop`    double(4, 3) default NULL, "
		lstrSql = lstrSql & "  `codclas` varchar(4) default NULL, "
		lstrSql = lstrSql & "  `ta` varchar(6) default NULL, "
		lstrSql = lstrSql & "  `zona`  char(3) default NULL, "
		lstrSql = lstrSql & "  `livro` char(2) default NULL, "
		lstrSql = lstrSql & "  `conta` varchar(8) default NULL, "
		lstrSql = lstrSql & "  `rota`  varchar(10) default NULL, "
		lstrSql = lstrSql & "  `banco_fatur` varchar(40) default NULL, "
		lstrSql = lstrSql & "  `banident` varchar(40) default NULL, "
		lstrSql = lstrSql & "  `agenc` varchar(4) default NULL, "
		lstrSql = lstrSql & "  `cc` varchar(12) default NULL, "
		lstrSql = lstrSql & "  `pagto_governo` char(1) NOT NULL default 'N', "
		lstrSql = lstrSql & "  `cpf_cnpj` varchar(18) default NULL, "
		lstrSql = lstrSql & "  `insc` varchar(25) default NULL, "
		lstrSql = lstrSql & "  `rg` varchar(35) default NULL, "
		lstrSql = lstrSql & "  `nomecons` varchar(85) default NULL, "
		lstrSql = lstrSql & "  `refcons` varchar(60) default NULL, "
		lstrSql = lstrSql & "  `uf` char(2) default NULL, "
		lstrSql = lstrSql & "  `cidade` varchar(60) default NULL, "
		lstrSql = lstrSql & "  `distrito` varchar(60) default NULL, "
		lstrSql = lstrSql & "  `bairro` varchar(60) default NULL, "
		lstrSql = lstrSql & "  `logradouro` varchar(60) default NULL, "
		lstrSql = lstrSql & "  `complemento` varchar(140) default NULL, "
		lstrSql = lstrSql & "  `cep` varchar(10) default NULL, "
		lstrSql = lstrSql & "  `entrega` int(11) default NULL, "
		lstrSql = lstrSql & "  `uf_entrega` varchar(2) default NULL, "
		lstrSql = lstrSql & "  `cid_entrega` varchar(60) default NULL, "
		lstrSql = lstrSql & "  `dis_entrega` varchar(60) default NULL, "
		lstrSql = lstrSql & "  `bai_entrega` varchar(60) default NULL, "
		lstrSql = lstrSql & "  `log_entrega` varchar(60) default NULL, "
		lstrSql = lstrSql & "  `com_entrega` varchar(100) NOT NULL default '', "
		lstrSql = lstrSql & "  `cep_entrega` varchar(10) default NULL, "
		lstrSql = lstrSql & "  `valortot` decimal(14, 2) default NULL, "
		lstrSql = lstrSql & "  `valorliq` decimal(14, 2) default NULL, "
		lstrSql = lstrSql & "  `vlrconsutrib` decimal(10, 2) default NULL, "
		lstrSql = lstrSql & "  `datavenc` date default '0000-00-00', "
		lstrSql = lstrSql & "  `dataapr` date default '0000-00-00', "
		lstrSql = lstrSql & "  `dataemissao` date default '0000-00-00', "
		lstrSql = lstrSql & "  `dataproxleit` date default '0000-00-00', "
		lstrSql = lstrSql & "  `dataleit` date default '0000-00-00', "
		lstrSql = lstrSql & "  `dataleitant` date default '0000-00-00', "
		lstrSql = lstrSql & "  `datapag` date default '0000-00-00', "
		lstrSql = lstrSql & "  `num_med` varchar(18) default NULL, "
		lstrSql = lstrSql & "  `const_med` double default NULL, "
		lstrSql = lstrSql & "  `fase` char(1) default NULL, "
		lstrSql = lstrSql & "  `tensao` varchar(10) default NULL, "
		lstrSql = lstrSql & "  `codhash` varchar(50) default NULL, "
		lstrSql = lstrSql & "  `codbarra` varchar(50) default NULL, "
		lstrSql = lstrSql & "  `dvcodbarra` varchar(4) default NULL, "
		lstrSql = lstrSql & "  `leit` double default NULL, "
		lstrSql = lstrSql & "  `leituraant` varchar(10) default NULL, "
		lstrSql = lstrSql & "  `consfaturado` double default NULL, "
		lstrSql = lstrSql & "  `conslido` double default NULL, "
		lstrSql = lstrSql & "  `valorconsumo` double default NULL, "
		lstrSql = lstrSql & "  `leitura_kvarh_atual` double default NULL, "
		lstrSql = lstrSql & "  `leitura_kvarh_anterior` double default NULL, "
		lstrSql = lstrSql & "  `consumo_kvarh` double default NULL, "
		lstrSql = lstrSql & "  `LeitReservadoAtu` double default '0', "
		lstrSql = lstrSql & "  `LeitReservadoAnt` double default '0', "
		lstrSql = lstrSql & "  `consumoreservado` double default NULL, "
		lstrSql = lstrSql & "  `vlrConsumoReservado` double default NULL, "
		lstrSql = lstrSql & "  `saldo_arred` double default '0', "
		lstrSql = lstrSql & "  `diasconsumo` varchar(2) default NULL, "
		lstrSql = lstrSql & "  `vlrdiario` double default NULL, "
		lstrSql = lstrSql & "  `mediaconsumodiario` double default NULL, "
		lstrSql = lstrSql & "  `mesmaiorconsumo` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `mesmenorconsumo` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `maiorconsumo` double default NULL, "
		lstrSql = lstrSql & "  `menorconsumo` double default NULL, "
		lstrSql = lstrSql & "  `mediaconsumo3meses` double default NULL, "
		lstrSql = lstrSql & "  `ocorrencia` varchar(5) default NULL, "
		lstrSql = lstrSql & "  `descocorrencia` varchar(25) default NULL, "
		lstrSql = lstrSql & "  `valorpend` double default '0', "
		lstrSql = lstrSql & "  `totalpend` int(11) default '0', "
		lstrSql = lstrSql & "  `descclasse` varchar(100) default NULL, "
		lstrSql = lstrSql & "  `fp` double(3, 2) default NULL, "
		lstrSql = lstrSql & "  `baseicms` double default NULL, "
		lstrSql = lstrSql & "  `aliqicms` double default NULL, "
		lstrSql = lstrSql & "  `vlricms` double default NULL, "
		lstrSql = lstrSql & "  `baseicms1` double default NULL, "
		lstrSql = lstrSql & "  `aliqicms1` double default NULL, "
		lstrSql = lstrSql & "  `vlricms1` double default NULL, "
		lstrSql = lstrSql & "  `baseicmstotal` double default '0', "
		lstrSql = lstrSql & "  `vlricmstotal` double default '0', "
		lstrSql = lstrSql & "  `basepis` double default NULL, "
		lstrSql = lstrSql & "  `aliqpis` double default NULL, "
		lstrSql = lstrSql & "  `vlrpis` double default NULL, "
		lstrSql = lstrSql & "  `basecofins` double default NULL, "
		lstrSql = lstrSql & "  `aliqcofins` double default NULL, "
		lstrSql = lstrSql & "  `vlrcofins` double default NULL, "
		lstrSql = lstrSql & "  `mensagem` varchar(255) default NULL, "
		lstrSql = lstrSql & "  `dec_meta` double default NULL, "
		lstrSql = lstrSql & "  `dec_rea` double default NULL, "
		lstrSql = lstrSql & "  `fec_meta` double default NULL, "
		lstrSql = lstrSql & "  `fec_rea` double default NULL, "
		lstrSql = lstrSql & "  `dic_meta` double default NULL, "
		lstrSql = lstrSql & "  `dic_rea` double default NULL, "
		lstrSql = lstrSql & "  `fic_meta` double default NULL, "
		lstrSql = lstrSql & "  `fic_rea` double default NULL, "
		lstrSql = lstrSql & "  `dmic` double default NULL, "
		lstrSql = lstrSql & "  `dmicM` double default NULL, "
		lstrSql = lstrSql & "  `refindicador` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `conjunto` varchar(255) default NULL, "
		lstrSql = lstrSql & "  `ret_irpj` double default '0', "
		lstrSql = lstrSql & "  `ret_pis` double default '0', "
		lstrSql = lstrSql & "  `ret_csll` double default '0', "
		lstrSql = lstrSql & "  `ret_cofins` double default '0', "
		lstrSql = lstrSql & "  `comp_energia` double default NULL, "
		lstrSql = lstrSql & "  `comp_transmissao` double default NULL, "
		lstrSql = lstrSql & "  `comp_distribuicao` double default NULL, "
		lstrSql = lstrSql & "  `comp_encargos_setoriais` double default NULL, "
		lstrSql = lstrSql & "  `comp_outros` double default NULL, "
		lstrSql = lstrSql & "  `itens_fatura` text default NULL, "
		lstrSql = lstrSql & "  `hist_mes_ano01` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `hist_diascon01` int default NULL, "
		lstrSql = lstrSql & "  `hist_datpgto01` date default NULL, "
		lstrSql = lstrSql & "  `hist_consumo01` double default NULL, "
		lstrSql = lstrSql & "  `hist_leitura01` double default NULL, "
		lstrSql = lstrSql & "  `hist_vlrfatu01` double default NULL, "
		lstrSql = lstrSql & "  `hist_ocorren01` int default NULL, "
		lstrSql = lstrSql & "  `hist_mes_ano02` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `hist_diascon02` int default NULL, "
		lstrSql = lstrSql & "  `hist_datpgto02` date default NULL, "
		lstrSql = lstrSql & "  `hist_consumo02` double default NULL, "
		lstrSql = lstrSql & "  `hist_leitura02` double default NULL, "
		lstrSql = lstrSql & "  `hist_vlrfatu02` double default NULL, "
		lstrSql = lstrSql & "  `hist_ocorren02` int default NULL, "
		lstrSql = lstrSql & "  `hist_mes_ano03` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `hist_diascon03` int default NULL, "
		lstrSql = lstrSql & "  `hist_datpgto03` date default NULL, "
		lstrSql = lstrSql & "  `hist_consumo03` double default NULL, "
		lstrSql = lstrSql & "  `hist_leitura03` double default NULL, "
		lstrSql = lstrSql & "  `hist_vlrfatu03` double default NULL, "
		lstrSql = lstrSql & "  `hist_ocorren03` int default NULL, "
		lstrSql = lstrSql & "  `hist_mes_ano04` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `hist_diascon04` int default NULL, "
		lstrSql = lstrSql & "  `hist_datpgto04` date default NULL, "
		lstrSql = lstrSql & "  `hist_consumo04` double default NULL, "
		lstrSql = lstrSql & "  `hist_leitura04` double default NULL, "
		lstrSql = lstrSql & "  `hist_vlrfatu04` double default NULL, "
		lstrSql = lstrSql & "  `hist_ocorren04` int default NULL, "
		lstrSql = lstrSql & "  `hist_mes_ano05` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `hist_diascon05` int default NULL, "
		lstrSql = lstrSql & "  `hist_datpgto05` date default NULL, "
		lstrSql = lstrSql & "  `hist_consumo05` double default NULL, "
		lstrSql = lstrSql & "  `hist_leitura05` double default NULL, "
		lstrSql = lstrSql & "  `hist_vlrfatu05` double default NULL, "
		lstrSql = lstrSql & "  `hist_ocorren05` int default NULL, "
		lstrSql = lstrSql & "  `hist_mes_ano06` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `hist_diascon06` int default NULL, "
		lstrSql = lstrSql & "  `hist_datpgto06` date default NULL, "
		lstrSql = lstrSql & "  `hist_consumo06` double default NULL, "
		lstrSql = lstrSql & "  `hist_leitura06` double default NULL, "
		lstrSql = lstrSql & "  `hist_vlrfatu06` double default NULL, "
		lstrSql = lstrSql & "  `hist_ocorren06` int default NULL, "
		lstrSql = lstrSql & "  `hist_mes_ano07` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `hist_diascon07` int default NULL, "
		lstrSql = lstrSql & "  `hist_datpgto07` date default NULL, "
		lstrSql = lstrSql & "  `hist_consumo07` double default NULL, "
		lstrSql = lstrSql & "  `hist_leitura07` double default NULL, "
		lstrSql = lstrSql & "  `hist_vlrfatu07` double default NULL, "
		lstrSql = lstrSql & "  `hist_ocorren07` int default NULL, "
		lstrSql = lstrSql & "  `hist_mes_ano08` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `hist_diascon08` int default NULL, "
		lstrSql = lstrSql & "  `hist_datpgto08` date default NULL, "
		lstrSql = lstrSql & "  `hist_consumo08` double default NULL, "
		lstrSql = lstrSql & "  `hist_leitura08` double default NULL, "
		lstrSql = lstrSql & "  `hist_vlrfatu08` double default NULL, "
		lstrSql = lstrSql & "  `hist_ocorren08` int default NULL, "
		lstrSql = lstrSql & "  `hist_mes_ano09` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `hist_diascon09` int default NULL, "
		lstrSql = lstrSql & "  `hist_datpgto09` date default NULL, "
		lstrSql = lstrSql & "  `hist_consumo09` double default NULL, "
		lstrSql = lstrSql & "  `hist_leitura09` double default NULL, "
		lstrSql = lstrSql & "  `hist_vlrfatu09` double default NULL, "
		lstrSql = lstrSql & "  `hist_ocorren09` int default NULL, "
		lstrSql = lstrSql & "  `hist_mes_ano10` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `hist_diascon10` int default NULL, "
		lstrSql = lstrSql & "  `hist_datpgto10` date default NULL, "
		lstrSql = lstrSql & "  `hist_consumo10` double default NULL, "
		lstrSql = lstrSql & "  `hist_leitura10` double default NULL, "
		lstrSql = lstrSql & "  `hist_vlrfatu10` double default NULL, "
		lstrSql = lstrSql & "  `hist_ocorren10` int default NULL, "
		lstrSql = lstrSql & "  `hist_mes_ano11` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `hist_diascon11` int default NULL, "
		lstrSql = lstrSql & "  `hist_datpgto11` date default NULL, "
		lstrSql = lstrSql & "  `hist_consumo11` double default NULL, "
		lstrSql = lstrSql & "  `hist_leitura11` double default NULL, "
		lstrSql = lstrSql & "  `hist_vlrfatu11` double default NULL, "
		lstrSql = lstrSql & "  `hist_ocorren11` int default NULL, "
		lstrSql = lstrSql & "  `hist_mes_ano12` varchar(7) default NULL, "
		lstrSql = lstrSql & "  `hist_diascon12` int default NULL, "
		lstrSql = lstrSql & "  `hist_datpgto12` date default NULL, "
		lstrSql = lstrSql & "  `hist_consumo12` double default NULL, "
		lstrSql = lstrSql & "  `hist_leitura12` double default NULL, "
		lstrSql = lstrSql & "  `hist_vlrfatu12` double default NULL, "
		lstrSql = lstrSql & "  `hist_ocorren12` int default NULL, "
		lstrSql = lstrSql & " PRIMARY KEY  (`numnf`, `mesano`), "
		lstrSql = lstrSql & " KEY `keyzona` (`zona`), "
		lstrSql = lstrSql & " KEY `keylivro` (`livro`), "
		lstrSql = lstrSql & " KEY `keyconta` (`conta`), "
		lstrSql = lstrSql & " KEY `keyrota` (`rota`), "
		lstrSql = lstrSql & " KEY `keyvalortot` (`valortot`), "
		lstrSql = lstrSql & " KEY `keycpf_cnpj` (`cpf_cnpj`) "
		lstrSql = lstrSql & " ) ENGINE=InnoDB DEFAULT CHARSET=latin1 "
		Call Executar(lstrSql)
	End Sub
	
	Public Sub FaturasNetInsere(ByVal astrFiltro As String, ByRef aBarraProgresso As System.Windows.Forms.ProgressBar, ByRef alblPerc As System.Windows.Forms.Label, ByRef alblInfo As System.Windows.Forms.Label, Optional ByVal ablnRecria As Boolean = False)
		'dados da fatura
		Dim lstrMesAno As String
		Dim ldblNumNf As Double
		Dim lstrItens As String
		Dim lstrIteImp As String
		Dim lstrIteRef As String
		Dim lstrIteImpCon As String
		Dim lstrIteImpPis As String
		Dim lstrIteImpCof As String
		Dim lstrIteImpIcm As String
		Dim lstrIteImpIlu As String
		Dim lstrIteImpDiv As String
		Dim ldblCfop As Double
		Dim lstrZona As String
		Dim lstrLivro As String
		Dim lstrConta As String
		Dim lstrRota As String
		Dim lstrBancoFatur As String
		Dim lstrBanIdent As String
		Dim lstrCpfCnpj As String
		Dim lstrNumMedidor As String
		Dim ldblConstMedid As Double
		Dim lstrFase As String
		Dim lstrTa As String
		Dim lstrTensao As String
		Dim lstrCodHash As String
		Dim ldblValorTot As Double
		Dim ldblValorLiq As Double
		Dim lstrCodBarra As String
		Dim lstrDvCodBar As String
		Dim lstrCodClas As String
		Dim lintDias As Short
		'dados da tabela de classe
		Dim lstrDsClas As String
		'datas da fatura
		Dim ldteVcto As Date
		Dim ldteEmissao As Date
		Dim ldteApreset As Date
		Dim ldteProxLeit As Date
		Dim ldteLeitAtu As Date
		Dim ldteLeitAnt As Date
		'dados de leitura
		Dim ldblLeituraAnt As Double
		Dim ldblLeituraAtu As Double
		Dim ldblLeituraKvarhAnt As Double
		Dim ldblLeituraKvarhAtu As Double
		Dim ldblConsumoKvarh As Double
		Dim ldblFp As Double
		Dim lintMedOcorrencia As Short
		Dim lstrDesOcorrencia As String
		Dim ldblLeitReservadoAtu As Double
		Dim ldblLeitReservadoAnt As Double
		Dim ldblVlrConsumoReserv As Double
		'dados de consumo
		Dim ldblConsumo As Double
		Dim ldblReservado As Double
		Dim ldblConsumFat As Double
		Dim ldblVlrConFat As Double
		'Dados da unidade consumidora
		Dim lstrAgenc As String
		Dim lstrCc As String
		Dim lstrPagtoGov As String
		Dim lstrNome As String
		Dim lstrInsc As String
		Dim lstrRg As String
		Dim lstrRgOrgao As String
		Dim lstrRgUf As String
		Dim ldblSldArred As Double
		'dados do logradouro
		Dim lstrUf As String
		Dim lstrCidade As String
		Dim lstrDistrito As String
		Dim lstrBairro As String
		Dim lstrEnd As String
		Dim lstrCompl As String
		Dim lstrQuadra As String
		Dim lstrLote As String
		Dim lstrNumero As String
		Dim lstrCep As String
		Dim lintEntrega As Short
		Dim lstrUfEnt As String
		Dim lstrCidEnt As String
		Dim lstrDisEnt As String
		Dim lstrBaiEnt As String
		Dim lstrEndEnt As String
		Dim lstrComEnt As String
		Dim lstrQuaEnt As String
		Dim lstrLotEnt As String
		Dim lstrNumEnt As String
		Dim lstrCepEnt As String
		'dados de tributação
		Dim ldblVlrCofins As Double
		Dim ldblVlrPis As Double
		Dim ldblVlrIcms As Double
		Dim ldblVlrIcms1 As Double
		Dim ldblBaseIcms As Double
		Dim ldblAliqIcms As Double
		Dim ldblBaseIcms1 As Double
		Dim ldblAliqIcms1 As Double
		Dim ldblBasePis As Double
		Dim ldblAliqPis As Double
		Dim ldblBaseCofins As Double
		Dim ldblAliqCofins As Double
		Dim ldblBasIcmsTotal As Double
		Dim ldblVlrIcmsTotal As Double
		'dados de retenção
		Dim ldblRetIrpj As Double
		Dim ldblRetPis As Double
		Dim ldblRetCsll As Double
		Dim ldblRetCofins As Double
		'dados da composição da tarifa
		Dim ldblCompEnergia As Double
		Dim ldblCompTransmissao As Double
		Dim ldblCompDistribuicao As Double
		Dim ldblCompEncargosSetoriais As Double
		Dim ldblCompOutros As Double
		'dados dos indicadores
		Dim ldblDecMeta As Double
		Dim ldblDecReal As Double
		Dim ldblFecMeta As Double
		Dim ldblFecReal As Double
		Dim ldblDicMeta As Double
		Dim ldblDicReal As Double
		Dim ldblFicMeta As Double
		Dim ldblFicReal As Double
		Dim ldblDmicRea As Double
		Dim ldblDmicMet As Double
		Dim lstrRefIndi As String
		'Historico da unidade consumidora
		Dim ldblMaiorCons As Double
		Dim ldblMenorCons As Double
		Dim lstrMesMaiorC As String
		Dim lstrMesMenorC As String
		Dim ldblMed3Meses As Double
		Dim ldblValorPed As Double
		Dim lintCtrl As Short
		Dim lintQutdePed As Short
		Dim lintMed3Meses As Short
		Dim lstrMesAnoH As String
		Dim ldtePgentoH As Date
		Dim ldblVlrFatH As Double
		Dim lintDiasCoH As Short
		Dim ldblConsumH As Double
		Dim ldblLeiturH As Double
		Dim lintOcMediH As Short
		'UPGRADE_WARNING: Lower bound of array lstrHMesAno was changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="0F1C9BE1-AF9D-476E-83B1-17D43BECFF20"'
		Dim lstrHMesAno(12) As String
		'UPGRADE_WARNING: Lower bound of array lintHDiasCo was changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="0F1C9BE1-AF9D-476E-83B1-17D43BECFF20"'
		Dim lintHDiasCo(12) As Short
		'UPGRADE_WARNING: Lower bound of array lintHOMedia was changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="0F1C9BE1-AF9D-476E-83B1-17D43BECFF20"'
		Dim lintHOMedia(12) As Short
		'UPGRADE_WARNING: Lower bound of array ldteHPagame was changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="0F1C9BE1-AF9D-476E-83B1-17D43BECFF20"'
		Dim ldteHPagame(12) As Date
		'UPGRADE_WARNING: Lower bound of array ldblHConsum was changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="0F1C9BE1-AF9D-476E-83B1-17D43BECFF20"'
		Dim ldblHConsum(12) As Double
		'UPGRADE_WARNING: Lower bound of array ldblHLeitur was changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="0F1C9BE1-AF9D-476E-83B1-17D43BECFF20"'
		Dim ldblHLeitur(12) As Double
		'UPGRADE_WARNING: Lower bound of array ldblHVlrFat was changed from 1 to 0. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="0F1C9BE1-AF9D-476E-83B1-17D43BECFF20"'
		Dim ldblHVlrFat(12) As Double
		
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		Dim lrstUnC As ADODB.Recordset
		lrstUnC = New ADODB.Recordset
		Dim lrstCla As ADODB.Recordset
		lrstCla = New ADODB.Recordset
		Dim lrstHis As ADODB.Recordset
		lrstHis = New ADODB.Recordset
		Dim lrstNet As ADODB.Recordset
		lrstNet = New ADODB.Recordset
		Dim lblnContinua As Boolean
		
		lstrSql = ""
		lstrSql = lstrSql & "SELECT * "
		lstrSql = lstrSql & "  FROM `nf` "
		lstrSql = lstrSql & " WHERE flgst = '' "
		lstrSql = lstrSql & "   AND grupo = 'B' "
		If ablnRecria = False Then
			lstrSql = lstrSql & "   AND NOT EXISTS(SELECT * FROM `faturasnet` "
			lstrSql = lstrSql & "                   WHERE `faturasnet`.`numnf` = `nf`.`numnf` "
			lstrSql = lstrSql & "                     AND `faturasnet`.`mesano` = `nf`.`mesano`  "
			lstrSql = lstrSql & "                     AND `faturasnet`.`valortot` = `nf`.`valortot` )"
		End If
		If Len(Trim(astrFiltro)) > 0 Then
			lstrSql = lstrSql & "   AND " & astrFiltro
		End If
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					Call BarraProgresso(aBarraProgresso, alblPerc, alblInfo, 0, .RecordCount, " faturas NET")
					While Not .EOF
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						ldblNumNf = CDbl(IIf(IsDbNull(.Fields("numnf").value), 0, .Fields("numnf").value))
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						lstrMesAno = Trim(IIf(IsDbNull(.Fields("mesano").value), "00/0000", .Fields("mesano").value))
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						ldblValorTot = CDbl(IIf(IsDbNull(.Fields("valortot").value), 0, .Fields("valortot").value))
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						ldblValorLiq = CDbl(IIf(IsDbNull(.Fields("valorliq").value), 0, .Fields("valorliq").value))
						lblnContinua = True
						'          lstrSql = ""
						'          lstrSql = lstrSql & "SELECT 1 FROM faturasnet WHERE numnf = " & ldblNumNF & " AND mesano = '" & lstrMesAno & "' AND valortot = " & Replace(ldblValorTot, ",", ".")
						'          Call Conectar(lstrSql, lrstNet)
						'          With lrstNet
						'            If .State = adStateOpen Then
						'              If .RecordCount > 0 Then
						'                lblnContinua = False
						'              End If
						'              Call .Close
						'            End If
						'          End With
						If lblnContinua Then
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrItens = IIf(IsDbNull(.Fields("itensserv").value), "", .Fields("itensserv").value)
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrTa = Trim(IIf(IsDbNull(.Fields("ta").value), "01B1", .Fields("ta").value))
							'Convenios, Diversos e Taxados
							lstrIteImp = ""
							lstrIteImpCon = ""
							lstrIteImpPis = ""
							lstrIteImpCof = ""
							lstrIteImpIcm = ""
							lstrIteImpIlu = ""
							lstrIteImpDiv = ""
							For IndCodServ = 1 To Len(Trim(lstrItens))
								Call BuscaCodItem(IndCodServ, lstrItens)
								lstrIteRef = Trim(RefCodServ)
								If Len(lstrIteRef) > 0 Then
									If InStr(1, lstrIteRef, ")") > 0 Then
										lstrIteRef = Left(lstrIteRef, InStr(1, lstrIteRef, ")"))
									End If
								End If
								'Consumo ou Reativo
								If IsNumeric(VlrCodServ) Then
									If CDbl(VlrCodServ) <> 0 Then
										If Left(codserv, 9) = "030202009" Or Left(codserv, 10) = "0302020012" Then
											lstrIteImpCon = lstrIteImpCon & IIf(Len(lstrIteImpCon) > 0, ";", "")
											lstrIteImpCon = lstrIteImpCon & codTodescri(codserv) & ";"
											lstrIteImpCon = lstrIteImpCon & lstrIteRef & ";"
											lstrIteImpCon = lstrIteImpCon & FormatNumber(BuscaVlrItem(lstrItens, codserv), 2)
										End If
										'Pis
										If Left(codserv, 10) = "0302020029" Then
											lstrIteImpPis = lstrIteImpPis & IIf(Len(lstrIteImpPis) > 0, ";", "")
											lstrIteImpPis = lstrIteImpPis & codTodescri(codserv) & ";"
											lstrIteImpPis = lstrIteImpPis & lstrIteRef & ";"
											lstrIteImpPis = lstrIteImpPis & FormatNumber(BuscaVlrItem(lstrItens, codserv), 2)
										End If
										'Cofins
										If Left(codserv, 10) = "0302020030" Then
											lstrIteImpCof = lstrIteImpCof & IIf(Len(lstrIteImpCof) > 0, ";", "")
											lstrIteImpCof = lstrIteImpCof & codTodescri(codserv) & ";"
											lstrIteImpCof = lstrIteImpCof & lstrIteRef & ";"
											lstrIteImpCof = lstrIteImpCof & FormatNumber(BuscaVlrItem(lstrItens, codserv), 2)
										End If
										'Icms
										If Left(codserv, 10) = "0302030014" Then
											lstrIteImpIcm = lstrIteImpIcm & IIf(Len(lstrIteImpIcm) > 0, ";", "")
											lstrIteImpIcm = lstrIteImpIcm & codTodescri(codserv) & ";"
											lstrIteImpIcm = lstrIteImpIcm & lstrIteRef & ";"
											lstrIteImpIcm = lstrIteImpIcm & FormatNumber(BuscaVlrItem(lstrItens, codserv), 2)
										End If
										'Iluminação
										If Left(codserv, 10) = "0301000003" Then
											lstrIteImpIlu = lstrIteImpIlu & IIf(Len(lstrIteImpIlu) > 0, ";", "")
											lstrIteImpIlu = lstrIteImpIlu & codTodescri(codserv) & ";"
											lstrIteImpIlu = lstrIteImpIlu & lstrIteRef & ";"
											lstrIteImpIlu = lstrIteImpIlu & FormatNumber(BuscaVlrItem(lstrItens, codserv), 2)
										End If
										'Diversos, taxas e convênios
										If Left(codserv, 4) = "9030" Or Left(codserv, 4) = "9040" Or Left(codserv, 4) = "9070" Or Left(codserv, 4) = "9080" Then
											lstrIteImpDiv = lstrIteImpDiv & IIf(Len(lstrIteImpDiv) > 0, ";", "")
											lstrIteImpDiv = lstrIteImpDiv & codTodescri(codserv) & ";"
											lstrIteImpDiv = lstrIteImpDiv & lstrIteRef & ";"
											lstrIteImpDiv = lstrIteImpDiv & FormatNumber(CDbl(Replace(VlrCodServ, ".", ",")), 2)
										End If
									End If
								End If
							Next IndCodServ
							If UCase(Mid(lstrTa, 3, 1)) = "B" Then
								lstrIteImp = lstrIteImp & lstrIteImpCon
								lstrIteImp = lstrIteImp & IIf(Len(lstrIteImpPis) > 0, ";", "") & lstrIteImpPis
								lstrIteImp = lstrIteImp & IIf(Len(lstrIteImpCof) > 0, ";", "") & lstrIteImpCof
								lstrIteImp = lstrIteImp & IIf(Len(lstrIteImpIcm) > 0, ";", "") & lstrIteImpIcm
								lstrIteImp = lstrIteImp & IIf(Len(lstrIteImpIlu) > 0, ";", "") & lstrIteImpIlu
								lstrIteImp = lstrIteImp & IIf(Len(lstrIteImpDiv) > 0, ";", "") & lstrIteImpDiv
								lstrIteImp = lstrIteImp & ";"
							End If
							ldblConsumo = Arredondar(BuscaVlrItem(lstrItens, "030201008"), 2)
							ldblReservado = Arredondar(BuscaVlrItem(lstrItens, "0302010044"), 2)
							ldblConsumFat = Arredondar(BuscaVlrItem(lstrItens, "030201009"), 2)
							ldblVlrConFat = Arredondar(BuscaVlrItem(lstrItens, "030202009"), 2)
							
							ldblLeituraAnt = Arredondar(BuscaVlrItem(lstrItens, "0302990040"), 2)
							ldblLeituraAtu = Arredondar(BuscaVlrItem(lstrItens, "0302990039"), 2)
							ldblLeituraKvarhAnt = Arredondar(BuscaVlrItem(lstrItens, "0302010046"), 2)
							ldblLeituraKvarhAtu = Arredondar(BuscaVlrItem(lstrItens, "0302010045"), 2)
							ldblConsumoKvarh = Arredondar(BuscaVlrItem(lstrItens, "0302010047"), 2)
							ldblFp = Arredondar(BuscaVlrItem(lstrItens, "0302030099"), 2)
							
							ldblVlrCofins = Arredondar(BuscaVlrItem(lstrItens, "0302020030"), 2)
							ldblVlrPis = Arredondar(BuscaVlrItem(lstrItens, "0302020029"), 2)
							ldblVlrIcms = Arredondar(BuscaVlrItem(lstrItens, "0302030009"), 2)
							ldblVlrIcms1 = Arredondar(BuscaVlrItem(lstrItens, "0302030010"), 2)
							ldblBaseIcms = Arredondar(BuscaVlrItem(lstrItens, "0302030001"), 2)
							ldblAliqIcms = Arredondar(BuscaVlrItem(lstrItens, "0302030002"), 2)
							ldblBaseIcms1 = Arredondar(BuscaVlrItem(lstrItens, "0302030003"), 2)
							ldblAliqIcms1 = Arredondar(BuscaVlrItem(lstrItens, "0302030013"), 2)
							ldblBasePis = Arredondar(BuscaVlrItem(lstrItens, "0302020033"), 2)
							ldblAliqPis = Arredondar(BuscaVlrItem(lstrItens, "0302990303"), 2)
							ldblBaseCofins = Arredondar(BuscaVlrItem(lstrItens, "0302020034"), 2)
							ldblAliqCofins = Arredondar(BuscaVlrItem(lstrItens, "0302990304"), 2)
							ldblBasIcmsTotal = Arredondar(BuscaVlrItem(lstrItens, "0302030015"), 2)
							ldblVlrIcmsTotal = Arredondar(BuscaVlrItem(lstrItens, "0302030014"), 2)
							
							lintMedOcorrencia = BuscaVlrItem(lstrItens, "90410000")
							lstrDesOcorrencia = BuscaRefItem(lstrItens, "90410000")
							ldblLeitReservadoAtu = Arredondar(BuscaVlrItem(lstrItens, "0302040019"), 2)
							ldblLeitReservadoAnt = Arredondar(BuscaVlrItem(lstrItens, "0302040020"), 2)
							ldblVlrConsumoReserv = Arredondar(BuscaVlrItem(lstrItens, "0302990044"), 2)
							
							ldblRetIrpj = Arredondar(BuscaVlrItem(lstrItens, "9090000004"), 2)
							ldblRetPis = Arredondar(BuscaVlrItem(lstrItens, "9090000001"), 2)
							ldblRetCsll = Arredondar(BuscaVlrItem(lstrItens, "9090000003"), 2)
							ldblRetCofins = Arredondar(BuscaVlrItem(lstrItens, "9090000002"), 2)
							
							ldblCompEnergia = Arredondar(BuscaVlrItem(lstrItens, "0302090001"), 2)
							ldblCompTransmissao = Arredondar(BuscaVlrItem(lstrItens, "0302090002"), 2)
							ldblCompDistribuicao = Arredondar(BuscaVlrItem(lstrItens, "0302090003"), 2)
							ldblCompEncargosSetoriais = Arredondar(BuscaVlrItem(lstrItens, "0302090004"), 2)
							ldblCompOutros = Arredondar(BuscaVlrItem(lstrItens, "0302090005"), 2)
							
							
							ldblDecMeta = Arredondar(BuscaVlrItem(lstrItens, "0302080101"), 2)
							ldblDecReal = Arredondar(BuscaVlrItem(lstrItens, "0302080001"), 2)
							ldblFecMeta = Arredondar(BuscaVlrItem(lstrItens, "0302080102"), 2)
							ldblFecReal = Arredondar(BuscaVlrItem(lstrItens, "0302080002"), 2)
							ldblDicMeta = Arredondar(BuscaVlrItem(lstrItens, "0302080103"), 2)
							ldblDicReal = Arredondar(BuscaVlrItem(lstrItens, "0302080003"), 2)
							ldblFicMeta = Arredondar(BuscaVlrItem(lstrItens, "0302080104"), 2)
							ldblFicReal = Arredondar(BuscaVlrItem(lstrItens, "0302080004"), 2)
							ldblDmicRea = Arredondar(BuscaVlrItem(lstrItens, "0302080105"), 2)
							ldblDmicMet = Arredondar(BuscaVlrItem(lstrItens, "0302080005"), 2)
							lstrRefIndi = BuscaRefItem(lstrItens, "0302080099")
							
							
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldblCfop = CDbl(IIf(IsDbNull(.Fields("cfop").value), 0, .Fields("cfop").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrZona = VB6.Format(Trim(IIf(IsDbNull(.Fields("zona").value), "0", .Fields("zona").value)), "000")
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrLivro = VB6.Format(Trim(IIf(IsDbNull(.Fields("livro").value), "0", .Fields("livro").value)), "00")
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrConta = VB6.Format(Trim(IIf(IsDbNull(.Fields("conta").value), "0", .Fields("conta").value)), "000000")
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrRota = VB6.Format(Trim(IIf(IsDbNull(.Fields("rota").value), "0", .Fields("rota").value)), "00000000")
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrCodClas = Trim(IIf(IsDbNull(.Fields("codclas").value), "0", .Fields("codclas").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lintDias = CShort(IIf(IsDbNull(.Fields("dias").value), 0, .Fields("dias").value))
							
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldteVcto = CDate(Trim(IIf(IsDbNull(.Fields("datavenc").value), "1900-01-01", .Fields("datavenc").value)))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldteEmissao = CDate(Trim(IIf(IsDbNull(.Fields("dataem").value), "1900-01-01", .Fields("dataem").value)))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldteApreset = CDate(Trim(IIf(IsDbNull(.Fields("dataapr").value), "1900-01-01", .Fields("dataapr").value)))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldteProxLeit = CDate(Trim(IIf(IsDbNull(.Fields("dataproxleit").value), "1900-01-01", .Fields("dataproxleit").value)))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldteLeitAtu = CDate(Trim(IIf(IsDbNull(.Fields("dataleit").value), "1900-01-01", .Fields("dataleit").value)))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldteLeitAnt = CDate(Trim(IIf(IsDbNull(.Fields("dataleitant").value), "1900-01-01", .Fields("dataleitant").value)))
							
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrBancoFatur = Trim(IIf(IsDbNull(.Fields("banco_fatur").value), "0", .Fields("banco_fatur").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrBanIdent = Trim(IIf(IsDbNull(.Fields("banident").value), "0", .Fields("banident").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrCpfCnpj = Trim(IIf(IsDbNull(.Fields("cpf_cnpj").value), "", .Fields("cpf_cnpj").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrNumMedidor = Trim(IIf(IsDbNull(.Fields("num_med").value), "", .Fields("num_med").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							ldblConstMedid = CDbl(IIf(IsDbNull(.Fields("const_med").value), 0, .Fields("const_med").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrFase = Trim(IIf(IsDbNull(.Fields("fase").value), "M", .Fields("fase").value))
							
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrTensao = Trim(IIf(IsDbNull(.Fields("tensao").value), "220", .Fields("tensao").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrCodHash = Trim(IIf(IsDbNull(.Fields("codhash").value), "", .Fields("codhash").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrCodBarra = Trim(IIf(IsDbNull(.Fields("codbarra").value), "", .Fields("codbarra").value))
							'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
							lstrDvCodBar = Trim(IIf(IsDbNull(.Fields("dvcodbarra").value), "", .Fields("dvcodbarra").value))
							
							lstrSql = ""
							If Mid(lstrTa, 3, 1) = "A" Then
								lstrSql = lstrSql & "SELECT `agenc`, `cc`, `pagto_governo`, `nome`, `insc`, `rg`, `rg_orgao`, `rg_uf`, `arredonda` AS `arredonda_temp`, "
								lstrSql = lstrSql & "       `uf`, `cidade`, `distrito`, `bairro`, `end`, `complement`, `quadra`, `lote`, `numero`, `cep`, `entrega`, "
								lstrSql = lstrSql & "       `uf_entrega`, `cid_entrega`, `dis_entrega`, `bai_entrega`, `end_entrega`, `compl_entrega`, `qua_entrega`, `lot_entrega`, `num_entrega`, `cep_entrega` "
								lstrSql = lstrSql & "  FROM `unida`"
								lstrSql = lstrSql & " WHERE `unida`.`zona`  = '" & lstrZona & "' "
								lstrSql = lstrSql & "   AND `unida`.`livro` = '" & lstrLivro & "' "
								lstrSql = lstrSql & "   AND `unida`.`conta` = '" & lstrConta & "' "
								lstrSql = lstrSql & " LIMIT 0, 1 "
							Else
								lstrSql = lstrSql & "SELECT `agenc`, `cc`, `pagto_governo`, `nome`, `insc`, `rg`, `rg_orgao`, `rg_uf`, `arredonda_temp`, "
								lstrSql = lstrSql & "       `uf`, `cidade`, `distrito`, `bairro`, `end`, `complement`, `quadra`, `lote`, `numero`, `cep`, `entrega`, "
								lstrSql = lstrSql & "       `uf_entrega`, `cid_entrega`, `dis_entrega`, `bai_entrega`, `end_entrega`, `compl_entrega`, `qua_entrega`, `lot_entrega`, `num_entrega`, `cep_entrega` "
								lstrSql = lstrSql & "  FROM `unidb`"
								lstrSql = lstrSql & " WHERE `unidb`.`zona`  = '" & lstrZona & "' "
								lstrSql = lstrSql & "   AND `unidb`.`livro` = '" & lstrLivro & "' "
								lstrSql = lstrSql & "   AND `unidb`.`conta` = '" & lstrConta & "' "
								lstrSql = lstrSql & " LIMIT 0, 1 "
							End If
							
							Call Conectar(lstrSql, lrstUnC)
							With lrstUnC
								If .State = ADODB.ObjectStateEnum.adStateOpen Then
									If .RecordCount > 0 Then
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrAgenc = Trim(IIf(IsDbNull(.Fields("agenc").value), "", .Fields("agenc").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrCc = Trim(IIf(IsDbNull(.Fields("cc").value), "", .Fields("cc").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrPagtoGov = Trim(IIf(IsDbNull(.Fields("pagto_governo").value), "N", .Fields("pagto_governo").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrNome = Trim(IIf(IsDbNull(.Fields("nome").value), "", .Fields("nome").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrInsc = Trim(IIf(IsDbNull(.Fields("insc").value), "", .Fields("insc").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrRg = Trim(IIf(IsDbNull(.Fields("rg").value), "", .Fields("rg").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrRgOrgao = Trim(IIf(IsDbNull(.Fields("rg_orgao").value), "", .Fields("rg_orgao").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrRgUf = Trim(IIf(IsDbNull(.Fields("rg_uf").value), "", .Fields("rg_uf").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										ldblSldArred = CDbl(IIf(IsDbNull(.Fields("arredonda_temp").value), 0, .Fields("arredonda_temp").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrUf = Trim(IIf(IsDbNull(.Fields("uf").value), "", .Fields("uf").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrCidade = Trim(IIf(IsDbNull(.Fields("cidade").value), "", .Fields("cidade").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrDistrito = Trim(IIf(IsDbNull(.Fields("distrito").value), "", .Fields("distrito").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrBairro = Trim(IIf(IsDbNull(.Fields("bairro").value), "", .Fields("bairro").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrEnd = Trim(IIf(IsDbNull(.Fields("end").value), "", .Fields("end").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrCompl = Trim(IIf(IsDbNull(.Fields("complement").value), "", .Fields("complement").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrQuadra = Trim(IIf(IsDbNull(.Fields("quadra").value), "", .Fields("quadra").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrLote = Trim(IIf(IsDbNull(.Fields("lote").value), "", .Fields("lote").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrNumero = Trim(IIf(IsDbNull(.Fields("numero").value), "", .Fields("numero").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrCep = Trim(IIf(IsDbNull(.Fields("cep").value), "", .Fields("cep").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lintEntrega = CShort(IIf(IsDbNull(.Fields("entrega").value), 0, .Fields("entrega").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrUfEnt = Trim(IIf(IsDbNull(.Fields("uf_entrega").value), "", .Fields("uf_entrega").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrCidEnt = Trim(IIf(IsDbNull(.Fields("cid_entrega").value), "", .Fields("cid_entrega").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrDisEnt = Trim(IIf(IsDbNull(.Fields("dis_entrega").value), "", .Fields("dis_entrega").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrBaiEnt = Trim(IIf(IsDbNull(.Fields("bai_entrega").value), "", .Fields("bai_entrega").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrEndEnt = Trim(IIf(IsDbNull(.Fields("end_entrega").value), "", .Fields("end_entrega").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrComEnt = Trim(IIf(IsDbNull(.Fields("compl_entrega").value), "", .Fields("compl_entrega").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrQuaEnt = Trim(IIf(IsDbNull(.Fields("qua_entrega").value), "", .Fields("qua_entrega").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrLotEnt = Trim(IIf(IsDbNull(.Fields("lot_entrega").value), "", .Fields("lot_entrega").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrNumEnt = Trim(IIf(IsDbNull(.Fields("num_entrega").value), "", .Fields("num_entrega").value))
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrCepEnt = Trim(IIf(IsDbNull(.Fields("cep_entrega").value), "", .Fields("cep_entrega").value))
									End If
									Call .Close()
								End If
							End With
							lstrSql = ""
							lstrSql = lstrSql & "SELECT `descricao` "
							lstrSql = lstrSql & "  FROM `classe` "
							lstrSql = lstrSql & " WHERE `codigo` = '" & lstrCodClas & "' "
							lstrSql = lstrSql & " LIMIT 0, 1"
							Call Conectar(lstrSql, lrstCla)
							With lrstCla
								If .State = ADODB.ObjectStateEnum.adStateOpen Then
									If .RecordCount > 0 Then
										'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
										lstrDsClas = Trim(IIf(IsDbNull(.Fields("descricao").value), "", .Fields("descricao").value))
									End If
									Call .Close()
								End If
							End With
							ldblMaiorCons = 0
							ldblMenorCons = 99999999
							ldblValorPed = 0
							lintQutdePed = 0
							ldblMed3Meses = 0
							lintMed3Meses = 0
							For lintCtrl = 1 To 12
								lstrHMesAno(lintCtrl) = "00/0000"
								lintHDiasCo(lintCtrl) = 0
								lintHOMedia(lintCtrl) = 0
								ldteHPagame(lintCtrl) = CDate("01/01/1900")
								ldblHConsum(lintCtrl) = 0
								ldblHLeitur(lintCtrl) = 0
								ldblHVlrFat(lintCtrl) = 0
							Next lintCtrl
							lintCtrl = 1
							lstrSql = ""
							lstrSql = lstrSql & "  SELECT nf.mesano, "
							lstrSql = lstrSql & "         IF(nf.valorliq<>0,nf.valorliq,nf.valortot) AS valorfat, "
							lstrSql = lstrSql & "         nf.datapag, "
							lstrSql = lstrSql & "         (nf.dias)+0 as dias, "
							lstrSql = lstrSql & "         nf.itensserv"
							lstrSql = lstrSql & "    FROM nf "
							lstrSql = lstrSql & "   WHERE nf.flgst <> 'C'"
							lstrSql = lstrSql & "     AND nf.zona  = '" & lstrZona & "' "
							lstrSql = lstrSql & "     AND nf.livro = '" & lstrLivro & "' "
							lstrSql = lstrSql & "     AND nf.conta = '" & lstrConta & "' "
							lstrSql = lstrSql & "     AND nf.mesano_ref <> '" & CInt(Right(lstrMesAno, 4) & Left(lstrMesAno, 2)) & "' "
							lstrSql = lstrSql & "     AND mesano_ref <= " & CInt(Right(lstrMesAno, 4) & Left(lstrMesAno, 2)) & " "
							lstrSql = lstrSql & "ORDER BY mesano_ref DESC "
							lstrSql = lstrSql & "   LIMIT 0, 12"
							Call Conectar(lstrSql, lrstHis)
							With lrstHis
								If .State = ADODB.ObjectStateEnum.adStateOpen Then
									If .RecordCount > 0 Then
										While Not .EOF
											'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
											lstrMesAnoH = Trim(IIf(IsDbNull(.Fields("mesano").value), "00/0000", .Fields("mesano").value))
											'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
											ldblVlrFatH = CDbl(IIf(IsDbNull(.Fields("valorfat").value), 0, .Fields("valorfat").value))
											'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
											ldtePgentoH = CDate(IIf(IsDbNull(.Fields("datapag").value Or .Fields("datapag").Value = "0000-00-00"), "1900-01-01", .Fields("datapag").value))
											'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
											lintDiasCoH = CShort(IIf(IsDbNull(.Fields("dias").value), 0, .Fields("dias").value))
											'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
											lstrItens = Trim(IIf(IsDbNull(.Fields("itensserv").value), "", .Fields("itensserv").value))
											If Len(Trim(lstrItens)) > 0 Then
												ldblConsumH = BuscaVlrItem(lstrItens, "030201008") + BuscaVlrItem(lstrItens, "0302010044")
												ldblLeiturH = BuscaVlrItem(lstrItens, "0302990039")
												lintOcMediH = BuscaVlrItem(lstrItens, "90410000")
												If ldblConsumH > ldblMaiorCons Then
													ldblMaiorCons = ldblConsumH
													lstrMesMaiorC = lstrMesAnoH
												End If
												If ldblConsumH < ldblMenorCons Then
													ldblMenorCons = ldblConsumH
													lstrMesMenorC = lstrMesAnoH
												End If
											Else
												ldblConsumH = 0
												ldblLeiturH = 0
												lintOcMediH = 0
											End If
											If ldtePgentoH = CDate("01/01/1900") Then
												ldblValorPed = ldblValorPed + ldblVlrFatH
												lintQutdePed = lintQutdePed + 1
											End If
											If lintCtrl <= 2 Then
												ldblMed3Meses = ldblMed3Meses + ldblConsumH
												lintMed3Meses = lintMed3Meses + 1
											End If
											lstrHMesAno(lintCtrl) = lstrMesAnoH
											lintHDiasCo(lintCtrl) = lintDiasCoH
											lintHOMedia(lintCtrl) = lintOcMediH
											ldteHPagame(lintCtrl) = ldtePgentoH
											ldblHConsum(lintCtrl) = ldblConsumH
											ldblHLeitur(lintCtrl) = ldblLeiturH
											ldblHVlrFat(lintCtrl) = ldblVlrFatH
											Call .MoveNext()
											lintCtrl = lintCtrl + 1
										End While
									End If
									Call .Close()
								End If
							End With
							If (ldblConsumo + ldblReservado) > ldblMaiorCons Then
								ldblMaiorCons = (ldblConsumo + ldblReservado)
							End If
							If (ldblConsumo + ldblReservado) < ldblMenorCons Then
								ldblMenorCons = (ldblConsumo + ldblReservado)
							End If
							ldblMed3Meses = ldblMed3Meses + (ldblConsumo + ldblReservado)
							lintMed3Meses = lintMed3Meses + 1
							If IsNumeric(lstrCpfCnpj) Then
								If Valida_CPF_CGC(lstrCpfCnpj) Then
									Call Executar("DELETE FROM faturasnet WHERE numnf = " & ldblNumNf & " AND mesano = '" & lstrMesAno & "' ")
									
									lstrSql = ""
									lstrSql = lstrSql & "INSERT INTO faturasnet SET " & vbCrLf
									lstrSql = lstrSql & "            numnf          = " & ldblNumNf & ", " & vbCrLf
									lstrSql = lstrSql & "            mesano         = '" & lstrMesAno & "', " & vbCrLf
									lstrSql = lstrSql & "            cfop           = " & Replace(CStr(ldblCfop), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            zona           = '" & lstrZona & "', " & vbCrLf
									lstrSql = lstrSql & "            livro          = '" & lstrLivro & "', " & vbCrLf
									lstrSql = lstrSql & "            conta          = '" & lstrConta & "', " & vbCrLf
									lstrSql = lstrSql & "            rota           = '" & lstrRota & "', " & vbCrLf
									lstrSql = lstrSql & "            codclas        = '" & lstrCodClas & "', " & vbCrLf
									lstrSql = lstrSql & "            datavenc       = '" & VB6.Format(IIf(ldteVcto = CDate("01/01/1900"), "0000-00-00", ldteVcto), "yyyy-MM-dd") & "', " & vbCrLf
									lstrSql = lstrSql & "            dataemissao    = '" & VB6.Format(IIf(ldteEmissao = CDate("01/01/1900"), "0000-00-00", ldteEmissao), "yyyy-MM-dd") & "', " & vbCrLf
									lstrSql = lstrSql & "            dataapr        = '" & VB6.Format(IIf(ldteApreset = CDate("01/01/1900"), "0000-00-00", ldteApreset), "yyyy-MM-dd") & "', " & vbCrLf
									lstrSql = lstrSql & "            dataproxleit   = '" & VB6.Format(IIf(ldteProxLeit = CDate("01/01/1900"), "0000-00-00", ldteProxLeit), "yyyy-MM-dd") & "', " & vbCrLf
									lstrSql = lstrSql & "            dataleit       = '" & VB6.Format(IIf(ldteLeitAtu = CDate("01/01/1900"), "0000-00-00", ldteLeitAtu), "yyyy-MM-dd") & "', " & vbCrLf
									lstrSql = lstrSql & "            dataleitant    = '" & VB6.Format(IIf(ldteLeitAnt = CDate("01/01/1900"), "0000-00-00", ldteLeitAnt), "yyyy-MM-dd") & "', " & vbCrLf
									lstrSql = lstrSql & "            banco_fatur    = '" & lstrBancoFatur & "', " & vbCrLf
									lstrSql = lstrSql & "            banident       = """ & lstrBanIdent & """, " & vbCrLf
									lstrSql = lstrSql & "            cpf_cnpj       = '" & lstrCpfCnpj & "', " & vbCrLf
									lstrSql = lstrSql & "            num_med        = '" & lstrNumMedidor & "', " & vbCrLf
									lstrSql = lstrSql & "            const_med      = " & Replace(CStr(ldblConstMedid), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            fase           = '" & lstrFase & "', " & vbCrLf
									lstrSql = lstrSql & "            ta             = '" & lstrTa & "', " & vbCrLf
									lstrSql = lstrSql & "            tensao         = '" & lstrTensao & "', " & vbCrLf
									lstrSql = lstrSql & "            codhash        = '" & lstrCodHash & "', " & vbCrLf
									lstrSql = lstrSql & "            valortot       = " & Replace(CStr(ldblValorTot), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            valorliq       = " & Replace(CStr(ldblValorLiq), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            codbarra       = '" & lstrCodBarra & "', " & vbCrLf
									lstrSql = lstrSql & "            dvcodbarra     = '" & lstrDvCodBar & "', " & vbCrLf
									
									lstrSql = lstrSql & "            diasconsumo        = " & lintDias & ", " & vbCrLf
									lstrSql = lstrSql & "            vlrdiario          = " & Replace(CStr(Arredondar(ldblVlrConFat / IIf(lintDias = 0, 1, lintDias), 2)), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            mediaconsumodiario = " & Replace(CStr(Arredondar(ldblConsumFat / IIf(lintDias = 0, 1, lintDias), 2)), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            maiorconsumo       = " & Replace(CStr(ldblMaiorCons), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            menorconsumo       = " & Replace(CStr(ldblMenorCons), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            mesmaiorconsumo    = '" & lstrMesMaiorC & "', " & vbCrLf
									lstrSql = lstrSql & "            mesmenorconsumo    = '" & lstrMesMenorC & "', " & vbCrLf
									lstrSql = lstrSql & "            valorpend          = " & Replace(CStr(ldblValorPed), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            totalpend          = " & lintQutdePed & ", " & vbCrLf
									lstrSql = lstrSql & "            mediaconsumo3meses = " & Replace(CStr(Arredondar(ldblMed3Meses / lintMed3Meses, 2)), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            ocorrencia         = " & lintMedOcorrencia & ", " & vbCrLf
									lstrSql = lstrSql & "            descocorrencia     = '" & lstrDesOcorrencia & "', " & vbCrLf
									
									lstrSql = lstrSql & "            consfaturado        = " & Replace(CStr(ldblConsumFat), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            conslido            = " & Replace(CStr(ldblConsumo), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            valorconsumo        = " & Replace(CStr(ldblVlrConFat), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            consumoreservado    = " & Replace(CStr(ldblReservado), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            LeitReservadoAtu    = " & Replace(CStr(ldblLeitReservadoAtu), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            LeitReservadoAnt    = " & Replace(CStr(ldblLeitReservadoAnt), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            vlrconsumoreservado = " & Replace(CStr(ldblVlrConsumoReserv), ",", ".") & ", " & vbCrLf
									
									lstrSql = lstrSql & "            baseicms      = " & Replace(CStr(ldblBaseIcms), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            aliqicms      = " & Replace(CStr(ldblAliqIcms), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            vlricms       = " & Replace(CStr(ldblVlrIcms), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            baseicms1     = " & Replace(CStr(ldblBaseIcms1), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            aliqicms1     = " & Replace(CStr(ldblAliqIcms1), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            vlricms1      = " & Replace(CStr(ldblVlrIcms1), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            basepis       = " & Replace(CStr(ldblBasePis), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            aliqpis       = " & Replace(CStr(ldblAliqPis), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            vlrpis        = " & Replace(CStr(ldblVlrPis), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            basecofins    = " & Replace(CStr(ldblBaseCofins), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            aliqcofins    = " & Replace(CStr(ldblAliqCofins), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            vlrcofins     = " & Replace(CStr(ldblVlrCofins), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            vlrconsutrib  = " & Replace(CStr(ldblVlrIcms + ldblVlrIcms1 + ldblVlrPis + ldblVlrCofins + ldblVlrConFat), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            baseicmstotal = " & Replace(CStr(ldblBasIcmsTotal), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            vlricmstotal  = " & Replace(CStr(ldblVlrIcmsTotal), ",", ".") & ", " & vbCrLf
									'indicadodres de continuidade
									lstrSql = lstrSql & "            dec_meta     = " & Replace(CStr(ldblDecMeta), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            dec_rea      = " & Replace(CStr(ldblDecReal), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            fec_meta     = " & Replace(CStr(ldblFecMeta), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            fec_rea      = " & Replace(CStr(ldblFecReal), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            dic_meta     = " & Replace(CStr(ldblDicMeta), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            dic_rea      = " & Replace(CStr(ldblDicReal), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            fic_meta     = " & Replace(CStr(ldblFicMeta), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            fic_rea      = " & Replace(CStr(ldblFicReal), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            dmic         = " & Replace(CStr(ldblDmicMet), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            dmicM        = " & Replace(CStr(ldblDmicRea), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            refindicador = '" & lstrRefIndi & "', " & vbCrLf
									lstrSql = lstrSql & "            conjunto     = 'CERGAL'," & vbCrLf
									'rentenção
									lstrSql = lstrSql & "            ret_irpj   = " & Replace(CStr(ldblRetIrpj), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            ret_pis    = " & Replace(CStr(ldblRetPis), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            ret_csll   = " & Replace(CStr(ldblRetCsll), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            ret_cofins = " & Replace(CStr(ldblRetCofins), ",", ".") & ", " & vbCrLf
									'componentes da tarifa e da fatura
									lstrSql = lstrSql & "            comp_energia            = " & Replace(CStr(ldblCompEnergia), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            comp_transmissao        = " & Replace(CStr(ldblCompTransmissao), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            comp_distribuicao       = " & Replace(CStr(ldblCompDistribuicao), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            comp_encargos_setoriais = " & Replace(CStr(ldblCompEncargosSetoriais), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            comp_outros             = " & Replace(CStr(ldblCompOutros), ",", ".") & ", " & vbCrLf
									
									lstrSql = lstrSql & "            leituraant             = " & Replace(CStr(ldblLeituraAnt), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            leit                   = " & Replace(CStr(ldblLeituraAtu), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            leitura_kvarh_anterior = " & Replace(CStr(ldblLeituraKvarhAnt), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            leitura_kvarh_atual    = " & Replace(CStr(ldblLeituraKvarhAtu), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            consumo_kvarh          = " & Replace(CStr(ldblConsumoKvarh), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            fp                     = " & Replace(CStr(ldblFp), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            agenc = '" & lstrAgenc & "', " & vbCrLf
									lstrSql = lstrSql & "            cc    = '" & lstrCc & "' , " & vbCrLf
									lstrSql = lstrSql & "            pagto_governo = '" & lstrPagtoGov & "', " & vbCrLf
									lstrSql = lstrSql & "            NomeCons    = """ & lstrNome & """, " & vbCrLf
									lstrSql = lstrSql & "            RefCons     = """ & lstrNome & """, " & vbCrLf
									lstrSql = lstrSql & "            insc        = '" & lstrInsc & "', " & vbCrLf
									lstrSql = lstrSql & "            rg          = '" & lstrRg & " " & lstrRgOrgao & " " & lstrRgUf & "', " & vbCrLf
									lstrSql = lstrSql & "            saldo_arred = " & Replace(CStr(ldblSldArred), ",", ".") & ", " & vbCrLf
									lstrSql = lstrSql & "            uf          = '" & lstrUf & "', " & vbCrLf
									lstrSql = lstrSql & "            cidade      = """ & lstrCidade & """, " & vbCrLf
									lstrSql = lstrSql & "            distrito    = """ & lstrDistrito & """, " & vbCrLf
									lstrSql = lstrSql & "            Bairro      = """ & lstrBairro & """, " & vbCrLf
									lstrSql = lstrSql & "            logradouro  = """ & lstrEnd & """, " & vbCrLf
									lstrSql = lstrSql & "            complemento = """ & lstrCompl & IIf(Len(lstrQuadra) > 0, " Q- " & lstrQuadra, "") & IIf(Len(lstrLote) > 0, " L- " & lstrLote, "") & IIf(Len(lstrNumero) > 0, " Nº " & lstrNumero, "") & """, " & vbCrLf
									lstrSql = lstrSql & "            cep         = '" & lstrCep & "', " & vbCrLf
									lstrSql = lstrSql & "            entrega     = " & lintEntrega & ", " & vbCrLf
									lstrSql = lstrSql & "            uf_entrega  = '" & lstrUfEnt & "', " & vbCrLf
									lstrSql = lstrSql & "            cid_entrega = """ & lstrCidEnt & """, " & vbCrLf
									lstrSql = lstrSql & "            dis_entrega = """ & lstrDisEnt & """, " & vbCrLf
									lstrSql = lstrSql & "            bai_entrega = """ & lstrBaiEnt & """, " & vbCrLf
									lstrSql = lstrSql & "            log_entrega = """ & lstrEndEnt & """, " & vbCrLf
									lstrSql = lstrSql & "            com_entrega = """ & lstrComEnt & IIf(Len(lstrQuaEnt) > 0, " Q- " & lstrQuaEnt, "") & IIf(Len(lstrLotEnt) > 0, " L- " & lstrLotEnt, "") & IIf(Len(lstrNumEnt) > 0, " Nº " & lstrNumEnt, "") & """, " & vbCrLf
									lstrSql = lstrSql & "            cep_entrega = '" & lstrCepEnt & "', " & vbCrLf
									lstrSql = lstrSql & "            itens_fatura = '" & lstrIteImp & "', " & vbCrLf
									For lintCtrl = 1 To 12
										lstrSql = lstrSql & "            hist_mes_ano" & VB6.Format(lintCtrl, "00") & " = '" & lstrHMesAno(lintCtrl) & "', " & vbCrLf
										lstrSql = lstrSql & "            hist_diascon" & VB6.Format(lintCtrl, "00") & " = " & lintHDiasCo(lintCtrl) & ", " & vbCrLf
										lstrSql = lstrSql & "            hist_datpgto" & VB6.Format(lintCtrl, "00") & " = '" & VB6.Format(IIf(ldteHPagame(lintCtrl) = CDate("01/01/1900"), "0000-00-00", ldteHPagame(lintCtrl)), "yyyy-MM-dd") & "', " & vbCrLf
										lstrSql = lstrSql & "            hist_consumo" & VB6.Format(lintCtrl, "00") & " = " & Replace(CStr(ldblHConsum(lintCtrl)), ",", ".") & ", " & vbCrLf
										lstrSql = lstrSql & "            hist_leitura" & VB6.Format(lintCtrl, "00") & " = " & Replace(CStr(ldblHLeitur(lintCtrl)), ",", ".") & ", " & vbCrLf
										lstrSql = lstrSql & "            hist_vlrfatu" & VB6.Format(lintCtrl, "00") & " = " & Replace(CStr(ldblHVlrFat(lintCtrl)), ",", ".") & ", " & vbCrLf
										lstrSql = lstrSql & "            hist_ocorren" & VB6.Format(lintCtrl, "00") & " = " & lintHOMedia(lintCtrl) & ", " & vbCrLf
									Next lintCtrl
									lstrSql = lstrSql & "            descclasse  = """ & lstrDsClas & """ "
									Call Executar(lstrSql)
									Call FaturasNetUnidades(lstrZona, lstrLivro, lstrConta, lstrCpfCnpj, UCase(Mid(lstrTa, 3, 1)), lstrNome)
								End If
							End If
						End If
						Call .MoveNext()
						Call BarraProgresso(aBarraProgresso, alblPerc, alblInfo, 1,  , " faturas NET")
						System.Windows.Forms.Application.DoEvents()
					End While
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		'UPGRADE_NOTE: Object lrstUnC may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstUnC = Nothing
		'UPGRADE_NOTE: Object lrstCla may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstCla = Nothing
		'UPGRADE_NOTE: Object lrstHis may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstHis = Nothing
		'UPGRADE_NOTE: Object lrstNet may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstNet = Nothing
	End Sub
	
	Public Sub FaturasNetRemove(ByVal astrFiltro As String)
		Dim lstrSql As String
		If Len(Trim(astrFiltro)) > 0 Then
			lstrSql = ""
			lstrSql = lstrSql & "DELETE FROM `faturasnet` WHERE " & astrFiltro
			Call Executar(lstrSql)
		End If
	End Sub
	
	Public Sub FaturasNetBaixa(ByVal astrFiltro As String, ByVal adtePagto As Date)
		Dim lstrSql As String
		If Len(Trim(astrFiltro)) > 0 Then
			lstrSql = ""
			lstrSql = lstrSql & "UPDATE `faturasnet` SET `datapag` = '" & VB6.Format(adtePagto, "yyyy-MM-dd") & "' "
			lstrSql = lstrSql & " WHERE " & astrFiltro
			Call Executar(lstrSql)
		End If
	End Sub
	
	Private Sub FaturasNetUnidades(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal astrCpfCnpj As String, ByVal astrGrupo As String, ByVal astrNome As String)
		Dim lblnAux As Boolean
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrSql = ""
		If IsNumeric(astrCpfCnpj) Then
			lstrSql = lstrSql & "SELECT `unidadesnet`.`cpf_cnpj`, "
			lstrSql = lstrSql & "       `unidadesnet`.`zona`, "
			lstrSql = lstrSql & "       `unidadesnet`.`livro`, "
			lstrSql = lstrSql & "       `unidadesnet`.`conta`, "
			lstrSql = lstrSql & "       `unidadesnet`.`grupo` "
			lstrSql = lstrSql & "  FROM `unidadesnet` "
			lstrSql = lstrSql & " WHERE `unidadesnet`.`cpf_cnpj` = '" & astrCpfCnpj & "' "
			lstrSql = lstrSql & "   AND `unidadesnet`.`zona`  = '" & astrZona & "' "
			lstrSql = lstrSql & "   AND `unidadesnet`.`livro` = '" & astrLivro & "' "
			lstrSql = lstrSql & "   AND `unidadesnet`.`conta` = '" & astrConta & "' "
			lstrSql = lstrSql & "   AND `unidadesnet`.`grupo` = '" & astrGrupo & "' "
			Call Conectar(lstrSql, lrstAux)
			lstrSql = ""
			With lrstAux
				If .State = ADODB.ObjectStateEnum.adStateOpen Then
					lblnAux = (.RecordCount > 0)
					If lblnAux Then
						lstrSql = lstrSql & "UPDATE `unidadesnet` SET " & vbCrLf
					Else
						lstrSql = lstrSql & "INSERT INTO `unidadesnet` SET " & vbCrLf
					End If
					lstrSql = lstrSql & "            `zona`     = '" & astrZona & "', " & vbCrLf
					lstrSql = lstrSql & "            `livro`    = '" & astrLivro & "', " & vbCrLf
					lstrSql = lstrSql & "            `conta`    = '" & astrConta & "', " & vbCrLf
					lstrSql = lstrSql & "            `cpf_cnpj` = '" & astrCpfCnpj & "', " & vbCrLf
					lstrSql = lstrSql & "            `grupo`    = '" & astrGrupo & "', " & vbCrLf
					lstrSql = lstrSql & "            `nomecons` = """ & astrNome & """ " & vbCrLf
					If lblnAux Then
						lstrSql = lstrSql & " WHERE `cpf_cnpj` = '" & astrCpfCnpj & "' "
						lstrSql = lstrSql & "   AND `zona`  = '" & astrZona & "' "
						lstrSql = lstrSql & "   AND `livro` = '" & astrLivro & "' "
						lstrSql = lstrSql & "   AND `conta` = '" & astrConta & "' "
						lstrSql = lstrSql & "   AND `grupo` = '" & astrGrupo & "' "
					End If
					Call .Close()
				End If
			End With
			Call Executar(lstrSql)
		End If
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
	End Sub
	
	Public Sub ArrumaItensImp(ByVal adblNumNf As Double, ByVal astrMesAno As String, ByVal astrTipoNf As String, ByVal aintTipo As Short, ByVal amfgAux As AxMSFlexGridLib.AxMSFlexGrid, Optional ByVal astrZona As String = "", Optional ByVal astrLivro As String = "", Optional ByVal astrConta As String = "")
		Dim lstrAuxiliar As String
		Dim lstrPrepara As String
		Dim lstrCodigo As String
		Dim lstrDescricao As String
		Dim lstrReferencia As String
		Dim lstrValor As String
		Dim lstrTexto As String
		Dim lstrIteImp As String
		Dim llngConta As Integer
		Dim lblnContinua As Boolean
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lblnContinua = True
		lrstAux = New ADODB.Recordset
		lstrSql = ""
		lstrSql = lstrSql & "SELECT `fatura`.`numnf`, `fatura`.`mesano`, `fatura`.`itensserv`, `fatura`.`itensimp` "
		lstrSql = lstrSql & ",`fatura`.`mesano_ref` "
		lstrSql = lstrSql & "  FROM " & astrTipoNf & " as `fatura` "
		lstrSql = lstrSql & " WHERE `fatura`.`mesano_ref` = " & CInt(Right(astrMesAno, 4) & Left(astrMesAno, 2)) & " "
		If adblNumNf > 0 Then
			lstrSql = lstrSql & "   AND `fatura`.`numnf`  = " & adblNumNf & " "
		End If
		If astrZona <> "" And astrLivro <> "" And astrConta <> "" Then
			lstrSql = lstrSql & "   AND `fatura`.`zona`  = '" & astrZona & "' "
			lstrSql = lstrSql & "   AND `fatura`.`livro` = '" & astrLivro & "' "
			lstrSql = lstrSql & "   AND `fatura`.`conta` = '" & astrConta & "' "
		End If
		If aintTipo = 1 Then
			lstrSql = lstrSql & "   AND (`fatura`.`itensimp` is null or `fatura`.`itensimp` ='') "
		End If
		Call Conectar(lstrSql, lrstAux)
		If lrstAux.RecordCount > 0 Then
			While Not lrstAux.EOF
				Call amfgAux.Clear()
				amfgAux.Rows = 0
				If adblNumNf = 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					adblNumNf = CDbl(IIf(IsDbNull(lrstAux.Fields("numnf").value), 0, lrstAux.Fields("numnf").value))
				End If
				'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
				lstrTexto = Trim(IIf(IsDbNull(lrstAux.Fields("itensserv").value), "", lrstAux.Fields("itensserv").value))
				'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
				lstrIteImp = Trim(IIf(IsDbNull(lrstAux.Fields("itensimp").value), "", lrstAux.Fields("itensimp").value))
				If aintTipo = 1 And lstrIteImp <> "" Then
					lblnContinua = False
				End If
				If lblnContinua Then
					With amfgAux
						For IndCodServ = 1 To Len(lstrTexto)
							Call BuscaCodItem(IndCodServ, lstrTexto)
							If Mid(codserv, 1, 9) = "030202009" Then
								.Rows = .Rows + 1
								.set_TextMatrix(.Rows - 1, 0, "01 - " & codserv)
								.set_TextMatrix(.Rows - 1, 1, codTodescri(codserv))
								.set_TextMatrix(.Rows - 1, 2, RefCodServ)
								.set_TextMatrix(.Rows - 1, 3, VB6.Format(Replace(VlrCodServ, ".", ","), "Standard"))
							End If
							If Mid(codserv, 1, 10) = "0302020012" Then
								.Rows = .Rows + 1
								.set_TextMatrix(.Rows - 1, 0, "02 - " & codserv)
								.set_TextMatrix(.Rows - 1, 1, codTodescri(codserv))
								.set_TextMatrix(.Rows - 1, 2, RefCodServ)
								.set_TextMatrix(.Rows - 1, 3, VB6.Format(Replace(VlrCodServ, ".", ","), "Standard"))
							End If
							If Mid(codserv, 1, 10) = "0302020029" Then
								.Rows = .Rows + 1
								.set_TextMatrix(.Rows - 1, 0, "03 - " & codserv)
								.set_TextMatrix(.Rows - 1, 1, codTodescri(codserv))
								.set_TextMatrix(.Rows - 1, 2, RefCodServ)
								.set_TextMatrix(.Rows - 1, 3, VB6.Format(Replace(VlrCodServ, ".", ","), "Standard"))
							End If
							If Mid(codserv, 1, 10) = "0302020030" Then
								.Rows = .Rows + 1
								.set_TextMatrix(.Rows - 1, 0, "04 - " & codserv)
								.set_TextMatrix(.Rows - 1, 1, codTodescri(codserv))
								.set_TextMatrix(.Rows - 1, 2, RefCodServ)
								.set_TextMatrix(.Rows - 1, 3, VB6.Format(Replace(VlrCodServ, ".", ","), "Standard"))
							End If
							If Mid(codserv, 1, 10) = "0302030014" Then
								.Rows = .Rows + 1
								.set_TextMatrix(.Rows - 1, 0, "05 - " & codserv)
								.set_TextMatrix(.Rows - 1, 1, codTodescri(codserv))
								.set_TextMatrix(.Rows - 1, 2, RefCodServ)
								.set_TextMatrix(.Rows - 1, 3, VB6.Format(Replace(VlrCodServ, ".", ","), "Standard"))
							End If
							If Mid(codserv, 1, 4) = "9030" Then
								.Rows = .Rows + 1
								.set_TextMatrix(.Rows - 1, 0, "06 - " & codserv)
								.set_TextMatrix(.Rows - 1, 1, codTodescri(codserv))
								.set_TextMatrix(.Rows - 1, 2, RefCodServ)
								.set_TextMatrix(.Rows - 1, 3, VB6.Format(Replace(VlrCodServ, ".", ","), "Standard"))
							End If
							If Mid(codserv, 1, 4) = "9040" Then
								.Rows = .Rows + 1
								.set_TextMatrix(.Rows - 1, 0, "07 - " & codserv)
								.set_TextMatrix(.Rows - 1, 1, codTodescri(codserv))
								.set_TextMatrix(.Rows - 1, 2, RefCodServ)
								.set_TextMatrix(.Rows - 1, 3, VB6.Format(Replace(VlrCodServ, ".", ","), "Standard"))
							End If
							If Mid(codserv, 1, 4) = "9070" Then
								.Rows = .Rows + 1
								.set_TextMatrix(.Rows - 1, 0, "08 - " & codserv)
								.set_TextMatrix(.Rows - 1, 1, codTodescri(codserv))
								.set_TextMatrix(.Rows - 1, 2, RefCodServ)
								.set_TextMatrix(.Rows - 1, 3, VB6.Format(Replace(VlrCodServ, ".", ","), "Standard"))
							End If
							If Mid(codserv, 1, 4) = "9080" Then
								.Rows = .Rows + 1
								.set_TextMatrix(.Rows - 1, 0, "09 - " & codserv)
								.set_TextMatrix(.Rows - 1, 1, codTodescri(codserv))
								.set_TextMatrix(.Rows - 1, 2, RefCodServ)
								.set_TextMatrix(.Rows - 1, 3, VB6.Format(Replace(VlrCodServ, ".", ","), "Standard"))
							End If
							If Mid(codserv, 1, 10) = "0301000003" Then
								.Rows = .Rows + 1
								.set_TextMatrix(.Rows - 1, 0, "10 - " & codserv)
								.set_TextMatrix(.Rows - 1, 1, codTodescri(codserv))
								.set_TextMatrix(.Rows - 1, 2, RefCodServ)
								.set_TextMatrix(.Rows - 1, 3, VB6.Format(Replace(VlrCodServ, ".", ","), "Standard"))
							End If
							If Mid(codserv, 1, 10) = "0302070005" Then
								.Rows = .Rows + 1
								.set_TextMatrix(.Rows - 1, 0, "11 - " & codserv)
								.set_TextMatrix(.Rows - 1, 1, codTodescri(codserv))
								.set_TextMatrix(.Rows - 1, 2, RefCodServ)
								.set_TextMatrix(.Rows - 1, 3, VB6.Format(Replace(VlrCodServ, ".", ","), "Standard"))
							End If
						Next IndCodServ
					End With
					With amfgAux
						If .Rows > 1 Then
							.Col = 0
							.Sort = MSFlexGridLib.SortSettings.flexSortStringAscending
							lstrAuxiliar = ""
							For llngConta = 0 To .Rows - 1
								If CDbl(.get_TextMatrix(llngConta, 3)) <> 0 Then
									If Len(lstrAuxiliar) <> 0 Then lstrAuxiliar = lstrAuxiliar & "\r\n"
									'
									lstrPrepara = ""
									lstrPrepara = lstrPrepara & Left(.get_TextMatrix(llngConta, 1) & .get_TextMatrix(llngConta, 2) & New String(" ", 50), 50)
									If Left(Trim(Mid(.get_TextMatrix(llngConta, 0), 5)), 4) = "9070" Then
										If IsNumeric(.get_TextMatrix(llngConta, 3)) Then
											If CDbl(.get_TextMatrix(llngConta, 3)) > 0 Then
												lstrPrepara = lstrPrepara & Right(New String(" ", 15) & "-" & VB6.Format(.get_TextMatrix(llngConta, 3), "Standard"), 15)
											Else
												lstrPrepara = lstrPrepara & Right(New String(" ", 15) & VB6.Format(.get_TextMatrix(llngConta, 3), "Standard"), 15)
											End If
										End If
									Else
										lstrPrepara = lstrPrepara & Right(New String(" ", 15) & VB6.Format(.get_TextMatrix(llngConta, 3), "Standard"), 15)
									End If
									lstrAuxiliar = lstrAuxiliar & lstrPrepara
									'
									'                lstrPrepara = Left(.TextMatrix(llngConta, 1) & .TextMatrix(llngConta, 2) & String(50, " "), 50) & Right(String(15, " ") & Format(.TextMatrix(llngConta, 3), "Standard"), 15)
									'                lstrAuxiliar = lstrAuxiliar & lstrPrepara
								End If
							Next llngConta
						End If
					End With
					lstrSql = ""
					lstrSql = lstrSql & "UPDATE " & astrTipoNf & " "
					lstrSql = lstrSql & "   SET itensImp = """ & lstrAuxiliar & """ "
					lstrSql = lstrSql & " WHERE numnf = " & adblNumNf & " "
					lstrSql = lstrSql & "   AND mesano_ref = " & CInt(Right(astrMesAno, 4) & Left(astrMesAno, 2)) & " "
					Call Executar(lstrSql)
				End If
				Call lrstAux.MoveNext()
				System.Windows.Forms.Application.DoEvents()
			End While
		End If
		If lrstAux.State = 1 Then Call lrstAux.Close()
	End Sub
	
	Public Sub InsereAuditoria(ByVal astrTexto As String)
		Dim lstrSql As String
		If glngUsuario_Id > 0 Then
			lstrSql = ""
			lstrSql = lstrSql & "INSERT INTO `auditor` SET "
			lstrSql = lstrSql & " `data_hora` = '" & VB6.Format(BuscaHoraBD, "yyyy-MM-dd hh:mm:ss") & "', "
			lstrSql = lstrSql & " `nomemaquina` = '" & gstrNmEstacao & "', "
			lstrSql = lstrSql & " `descricao` = '" & astrTexto & "', "
			lstrSql = lstrSql & " `cod_usuario` = " & glngUsuario_Id & ", "
			lstrSql = lstrSql & " `login_usuario` = '" & gstrUsuario_Nome & "' "
			Call Executar(lstrSql)
		End If
	End Sub
	
	Public Function PegaCargaInstalada(ByVal alngUnidId As Integer, ByVal astrGrupo As String) As Double
		Dim llngCod As Integer
		Dim ldblQtde As Double
		Dim ldblCarga As Double
		Dim ldblTotal As Double
		Dim lstrSql As String
		Dim lrstUnid As ADODB.Recordset
		Dim lrstEqui As ADODB.Recordset
		lrstUnid = New ADODB.Recordset
		lrstEqui = New ADODB.Recordset
		ldblTotal = 0
		lstrSql = ""
		lstrSql = lstrSql & "SELECT * "
		lstrSql = lstrSql & "  FROM cargaunid "
		lstrSql = lstrSql & " WHERE unid_id = " & alngUnidId & " "
		lstrSql = lstrSql & "   AND grupo   = '" & astrGrupo & "' "
		Call Conectar(lstrSql, lrstUnid)
		With lrstUnid
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					While Not .EOF
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						ldblQtde = CDbl(IIf(IsDbNull(.Fields("qtd").value), 0, .Fields("qtd").value))
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						llngCod = CInt(IIf(IsDbNull(.Fields("cod_equipamento").value), 0, .Fields("cod_equipamento").value))
						lstrSql = ""
						lstrSql = lstrSql & "SELECT * "
						lstrSql = lstrSql & "  FROM cargaequip "
						lstrSql = lstrSql & " WHERE cod_equipamento = " & llngCod & " "
						Call Conectar(lstrSql, lrstEqui)
						With lrstEqui
							If .State = ADODB.ObjectStateEnum.adStateOpen Then
								If .RecordCount > 0 Then
									'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
									ldblCarga = CDbl(IIf(IsDbNull(.Fields("carga").value), 0, .Fields("carga").value))
								End If
								Call .Close()
							End If
						End With
						ldblCarga = ldblCarga * ldblQtde
						ldblTotal = ldblTotal + ldblCarga
						Call .MoveNext()
					End While
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstUnid may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstUnid = Nothing
		'UPGRADE_NOTE: Object lrstEqui may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstEqui = Nothing
		PegaCargaInstalada = ldblTotal
	End Function
	
	Public Function RetornaDescricaoGrupoTarifa(ByVal astrTarifa As String) As Object
		Dim lstrRetorno As String
		
		Select Case astrTarifa
			Case Is = "B1"
				lstrRetorno = astrTarifa & " - Residencial"
			Case Is = "B2"
				lstrRetorno = astrTarifa & " - Rural"
			Case Is = "B4"
				lstrRetorno = astrTarifa & " - Iluminação pública"
			Case Is = "A4"
				lstrRetorno = "A4 - Convencional"
			Case Is = "AA"
				lstrRetorno = "A4 - Horosazonal azul"
			Case Is = "AV"
				lstrRetorno = "A4 - Horosazonal verde"
			Case Is = "AL"
				lstrRetorno = "A4 - Livre"
			Case Is = "AS"
				lstrRetorno = "A4 - Suprimento"
			Case Is = "AX"
				lstrRetorno = "A4 - Horo-sazonal suprimento"
			Case Else
				lstrRetorno = "B3 - Demais classes"
		End Select
		'UPGRADE_WARNING: Couldn't resolve default property of object RetornaDescricaoGrupoTarifa. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
		RetornaDescricaoGrupoTarifa = lstrRetorno
	End Function
	
	Public Function RetornaNomeConsumidor(ByVal astrZona As String, ByVal astrLivro As String, ByVal astrConta As String, ByVal alngUnidId As Integer, ByVal alngConsId As Integer, ByVal astrGrupo As String, Optional ByRef astrSituacao As String = "") As String
		Dim lstrNome As String
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		astrSituacao = "L"
		lstrNome = ""
		lstrSql = ""
		lstrSql = lstrSql & "SELECT `unid_id`, `zona`, `livro`, `conta`, `nome`, `situacao` " & vbCrLf
		lstrSql = lstrSql & "  FROM `unid" & LCase(Left(astrGrupo, 1)) & "` " & vbCrLf
		lstrSql = lstrSql & " WHERE `unid_id` = " & alngUnidId & vbCrLf
		lstrSql = lstrSql & "   AND `cons_id` = " & alngConsId
		lstrSql = lstrSql & "   AND `zona`    = " & astrZona
		lstrSql = lstrSql & "   AND `livro`   = " & astrLivro
		lstrSql = lstrSql & "   AND `conta`   = " & astrConta
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					'UPGRADE_WARNING: Couldn't resolve default property of object Interaction.IIf(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					lstrNome = Trim(IIf(IsDbNull(.Fields("nome").value), "EM BRANCO", .Fields("nome").value))
					'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
					'UPGRADE_WARNING: Couldn't resolve default property of object Interaction.IIf(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
					astrSituacao = Trim(IIf(IsDbNull(.Fields("situacao").value), "L", .Fields("situacao").value))
				End If
				Call .Close()
			End If
		End With
		If CInt(Len(lstrNome)) = 0 Then
			lstrSql = ""
			lstrSql = lstrSql & "SELECT `consreg`, `nome` " & vbCrLf
			lstrSql = lstrSql & "  FROM `consum` " & vbCrLf
			lstrSql = lstrSql & " WHERE `consreg` = " & alngConsId
			Call Conectar(lstrSql, lrstAux)
			With lrstAux
				If .State = ADODB.ObjectStateEnum.adStateOpen Then
					If .RecordCount > 0 Then
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						'UPGRADE_WARNING: Couldn't resolve default property of object Interaction.IIf(). Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
						lstrNome = Trim(IIf(IsDbNull(.Fields("nome").value), "EM BRANCO", .Fields("nome").value))
					Else
						lstrNome = "NOME NÃO ENCONTRADO"
					End If
					Call .Close()
				End If
			End With
		End If
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		RetornaNomeConsumidor = lstrNome
	End Function
	
	Public Function GetErrosVB(ByVal ErroNumber As Integer, Optional ByVal Descricao As String = "") As String
		Dim lstrErro(9000) As String
		lstrErro(0) = "Nenhum erro "
		lstrErro(3) = "Retorno sem GoSub "
		lstrErro(5) = "Chamada de procedimento ou argumento não é válido "
		lstrErro(6) = "Estouro de capacidade "
		lstrErro(7) = "Fora de memória "
		lstrErro(9) = "Subscrito fora do intervalo "
		lstrErro(10) = "Esta matriz é fixa ou temporariamente bloqueada "
		lstrErro(11) = "Divisão por zero "
		lstrErro(13) = "tipos incompatíveis "
		lstrErro(14) = "Espaço fora de sequência de caracteres "
		lstrErro(16) = "Expressão demasiadamente complexa"
		lstrErro(17) = "Não é possível executar a operação solicitada "
		lstrErro(18) = "Interrupção do usuário ocorreu"
		lstrErro(20) = "Continuar sem erro"
		lstrErro(28) = "Falta de espaço de pilha "
		lstrErro(35) = "Sub ou Função não definida "
		lstrErro(47) = "Muitas DLL de aplicativos clientes"
		lstrErro(48) = "Erro ao carregar a DLL "
		lstrErro(49) = "Convenção de chamada DLL inválida"
		lstrErro(51) = "Erro interno "
		lstrErro(52) = "Número ou nome de arquivo inválido"
		lstrErro(53) = "Arquivo não encontrado "
		lstrErro(54) = "Modo Bad file"
		lstrErro(55) = "O arquivo já em aberto"
		lstrErro(57) = "Erro de dispositivo de E/S"
		lstrErro(58) = "O arquivo já existe"
		lstrErro(59) = "Comprimento de registro inválido"
		lstrErro(61) = "Disco cheio "
		lstrErro(62) = "Entrada depois do fim do arquivo"
		lstrErro(63) = "Número de registro inválido"
		lstrErro(67) = "Há arquivos demais"
		lstrErro(68) = "Dispositivo não disponível"
		lstrErro(70) = "Permissão negada "
		lstrErro(71) = "Disco não está pronto"
		lstrErro(74) = "Não é possível renomear com unidade diferente"
		lstrErro(75) = "Erro de acesso Caminho/Arquivo"
		lstrErro(76) = "Caminho não encontrado"
		lstrErro(91) = "Variável Objeto ou variável de bloco With não atribuída"
		lstrErro(92) = "Loop For não inicializado "
		lstrErro(93) = "Seqüência de caracteres de padrão inválido"
		lstrErro(94) = "Uso inválido de Null"
		lstrErro(95) = "Erro definido pelo aplicativo ou por objetos"
		lstrErro(96) = "Não é possível coletar eventos do objeto porque o objeto já está sendo acionado de eventos para o número máximo de receptores de eventos suporta"
		lstrErro(97) = "Não é possível telefonar amigo função no objeto que não é uma instância de definição de classe"
		lstrErro(98) = "Uma chamada de propriedade ou método não pode incluir uma referência a um objeto particular, tanto como um argumento quanto como um valor de retorno"
		lstrErro(100) = "A classe não implementa a interface sistema.Collections.ICollection"
		lstrErro(298) = "Recurso do sistema ou DLL não pôde ser carregado "
		lstrErro(320) = "Não é possível usar nomes de dispositivo de caractere em nomes de arquivo especificados "
		lstrErro(321) = "Formato de arquivo inválido"
		lstrErro(322) = "Não é possível criar arquivo temporário necessário"
		lstrErro(325) = "Formato inválido no arquivo de recurso"
		lstrErro(327) = "Valor de dados nomeado não encontrado "
		lstrErro(328) = "Parâmetro inválido; Não é possível gravar arrays "
		lstrErro(335) = "Não foi possível acessar o Registro do sistema "
		lstrErro(336) = "Componente ActiveX Não Registrado Corretamente "
		lstrErro(337) = "Componente ActiveX não encontrado "
		lstrErro(338) = "Componente ActiveX não foi executado corretamente "
		lstrErro(360) = "Objeto já carregado "
		lstrErro(361) = "Não é possível carregar ou descarregar este objeto "
		lstrErro(363) = "O controle ActiveX especificado não foi encontrado "
		lstrErro(364) = "Objeto foi descarregado "
		lstrErro(365) = "Não é possível descarregar dentro neste contexto "
		lstrErro(368) = "O arquivo especificado está desatualizado "
		lstrErro(371) = "O objeto especificado não pode ser usado como um formulário do proprietário para Show"
		lstrErro(380) = "O valor da propriedade é inválido"
		lstrErro(381) = "Índice de matriz de propriedade não é válido"
		lstrErro(382) = "Não é suportado em time de execução do conjunto"
		lstrErro(383) = "Definições não suportadas "
		lstrErro(385) = "Índice de matriz de propriedade necessário"
		lstrErro(387) = "Conjunto não permitido"
		lstrErro(393) = "Obtenha não suportada em time de execução"
		lstrErro(394) = "Obter sem suporte "
		lstrErro(400) = "Formulário já exibido; não é possível mostrar modalmente "
		lstrErro(402) = "O código deve fechar formulário modal superior primeiro "
		lstrErro(422) = "Propriedade não encontrada"
		lstrErro(423) = "Propriedade ou método não encontrado"
		lstrErro(424) = "Objeto obrigatório "
		lstrErro(429) = "Não é possível criar componente ActiveX"
		lstrErro(430) = "Classe não oferece suporte à automação ou não dá suporte para interface esperada"
		lstrErro(432) = "Nome de arquivo ou nome da classe não foi encontrado durante operação de automação "
		lstrErro(438) = "Objeto não oferece suporte a essa propriedade ou método "
		lstrErro(440) = "Erros de automação"
		lstrErro(442) = "Conexão para biblioteca de tipo ou biblioteca de objeto para processo remoto foi perdida."
		lstrErro(443) = "Objeto de automação não tem um valor padrão"
		lstrErro(445) = "Objeto não suporta esta ação "
		lstrErro(446) = "Objeto não dá suporte para argumentos nomeados"
		lstrErro(447) = "Objeto não dá suporte à configuração da localidade atual "
		lstrErro(448) = "Argumento nomeado não encontrado "
		lstrErro(449) = "Argumento não opcional "
		lstrErro(450) = "Número errado de argumentos ou atribuição de propriedade não é válida"
		lstrErro(451) = "Propriedade deixa procedimento não definido e propriedade que recebe procedimento não retornou um objeto"
		lstrErro(452) = "Ordinal não é válido"
		lstrErro(453) = "Função DLL especificada não encontrada"
		lstrErro(454) = "Recurso de código não encontrado"
		lstrErro(455) = "Erro de bloqueio de recursos de código"
		lstrErro(457) = "Essa chave já está associada um elemento desta coleção"
		lstrErro(458) = "Variável usa um tipo de automação não tem suportado no Visual Basic"
		lstrErro(459) = "Objeto ou classe não possui suporte para o conjunto de eventos"
		lstrErro(460) = "Formato da área de transferência não é válido"
		lstrErro(461) = "Método ou membro de dados não encontrado"
		lstrErro(462) = "O servidor remoto não existe ou está não disponível "
		lstrErro(463) = "Classe não registrada na máquina local"
		lstrErro(481) = "Imagem não é válida."
		lstrErro(482) = "Erro com a Impressora"
		lstrErro(735) = "Não é possível salvar arquivo para TEMP"
		lstrErro(744) = "Texto de pesquisa não encontrado"
		lstrErro(746) = "Substituições muito longas"
		lstrErro(999) = "Declaração Stop encontrada  "
		lstrErro(1000) = "Erros internos do Fatwin"
		lstrErro(1001) = "O mês e ano do arquivo de indicadores não é igual ao mês e ano informado!"
		GetErrosVB = IIf(lstrErro(ErroNumber) <> "", lstrErro(ErroNumber), Descricao) & vbCrLf & "Entre em contando com o Administrador do Sistema."
	End Function
	
	
	Public Function BuscaNmCidade(Optional ByVal astrZona As String = "", Optional ByVal astrCodigo As String = "", Optional ByVal llngCodigo As Integer = 0) As String
		Dim lstrRet As String
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lstrRet = ""
		If astrZona <> "" Or astrCodigo <> "" Or llngCodigo <> 0 Then
			lstrSql = ""
			lstrSql = lstrSql & "SELECT * "
			lstrSql = lstrSql & "  FROM " & gstrDataBase & ".`munic` "
			lstrSql = lstrSql & " WHERE 1 = 1"
			If astrZona <> "" Then
				lstrSql = lstrSql & "   AND `zona` = '" & astrZona & "' "
			End If
			If astrCodigo <> "" Then
				lstrSql = lstrSql & "   AND `cod` = '" & astrCodigo & "' "
			End If
			If llngCodigo <> 0 Then
				lstrSql = lstrSql & "   AND `codnum` = " & llngCodigo & " "
			End If
			lstrSql = lstrSql & " LIMIT 0, 1 "
			Call Conectar(lstrSql, lrstAux)
			With lrstAux
				If .State = ADODB.ObjectStateEnum.adStateOpen Then
					If .RecordCount > 0 Then
						'UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
						lstrRet = Trim(IIf(IsDbNull(.Fields("nome").value), "", .Fields("nome").value))
					End If
					Call .Close()
				End If
			End With
		End If
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		BuscaNmCidade = lstrRet
	End Function
	
	Public Function VerificaExisteRegistro(ByVal astrTabela As String, ByVal astrCondicao As String) As Boolean
		Dim lblnRet As Boolean
		Dim lstrSql As String
		Dim lrstAux As ADODB.Recordset
		lrstAux = New ADODB.Recordset
		lblnRet = False
		lstrSql = "SELECT * FROM " & astrTabela & " WHERE " & astrCondicao
		Call Conectar(lstrSql, lrstAux)
		With lrstAux
			If .State = ADODB.ObjectStateEnum.adStateOpen Then
				If .RecordCount > 0 Then
					lblnRet = True
				End If
				Call .Close()
			End If
		End With
		'UPGRADE_NOTE: Object lrstAux may not be destroyed until it is garbage collected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6E35BFF6-CD74-4B09-9689-3E1A43DF8969"'
		lrstAux = Nothing
		VerificaExisteRegistro = lblnRet
	End Function
End Module