salvador
11-06-2015 12:17:01
Amigos;
Tenho uma variável publica chamada DataBal, onde armazena um data! Essa variável eu já estou utilizando para alimentar uma base de dados.
A macro funciona assim: Abri o arquivo TXT gerar uma base de dados e alimenta uma outra base de dados.
Estou tentando criar uma forma de validar uma coluna dessa base. Se a data do txt (DataBal) já existir nessa outra base de dados, então para a execução da macro.
Só que me vejo parado em dois problemas:
1 - A Variável armazena os valores como texto 42005 e na base de dados o formato está em data! Como eu posso transformar essa variável em data?
2 - Se o período já existir, gostaria que a macro terminasse!
Abaixo o código que estou com dificuldade!
Abaixo o código todo da minha macro:
Talvez tenha outra forma de fazer essa validação! Se vocês puderem me ajudar!
Desculpe as gambs da macro, mas funciona assim e ganho um tempão com isso!
Abraços e Obrigado
Tenho uma variável publica chamada DataBal, onde armazena um data! Essa variável eu já estou utilizando para alimentar uma base de dados.
A macro funciona assim: Abri o arquivo TXT gerar uma base de dados e alimenta uma outra base de dados.
Estou tentando criar uma forma de validar uma coluna dessa base. Se a data do txt (DataBal) já existir nessa outra base de dados, então para a execução da macro.
Só que me vejo parado em dois problemas:
1 - A Variável armazena os valores como texto 42005 e na base de dados o formato está em data! Como eu posso transformar essa variável em data?
2 - Se o período já existir, gostaria que a macro terminasse!
Abaixo o código que estou com dificuldade!
Código: Selecionar todos
For Each Per In [A2:A1000]
If DataBal = Per Then
MsgBox "O PERÍODO JÁ EXISTE"
Exit For
End If
Next Per
Abaixo o código todo da minha macro:
Código: Selecionar todos
Public DataBal As String
Sub Gerar_Bal_TEC()
Form_TEC.Show
'Seleção dos arquivos
filenames = Application.GetOpenFilename(, , , , True)
counter = 1
k = 1
'ubound determina quantos arquivos serão selecionados
While counter <= UBound(filenames)
'Abre os arquivos selecionados
Workbooks.Open filenames(counter)
'Acertando o relatório do sistema
Application.ScreenUpdating = False
Workbooks.OpenText Filename:=filenames(counter), Origin:=xlWindows, StartRow:=1, DataType:=xlFixedWidth, FieldInfo:= _
Array(Array(0, 1), Array(12, 1), Array(14, 1), Array(79, 1), Array(98, 1), Array(100, 1), _
Array(118, 1), Array(137, 1), Array(156, 1)), TrailingMinusNumbers:=True
' INSERINDO FÓRMULA PARA BUSCAR A DATA DO BALANCETE
Range("P3").Select
ActiveCell.FormulaR1C1 = _
"=DATEVALUE(TRIM(MID(CONCATENATE(RC[-15],RC[-14],RC[-13]),FIND("":"",CONCATENATE(RC[-15],RC[-14],RC[-13]),1)+1,FIND(""A"",CONCATENATE(RC[-15],RC[-14],RC[-13]),1)-FIND("":"",CONCATENATE(RC[-15],RC[-14],RC[-13]),1)-2)))"
Range("P4").Select
' VARIAVEL PARA ARMAZENAR A DATA
DataBal = Range("P3").Text
'EXCLUINDO A COLUNA B
Columns("B:B").Select
Selection.Delete Shift:=xlToLeft
' SELECIONA TODA A PLANILHA E SUBSTITUI SINAL DE = POR VAZIO
Cells.Select
Selection.Replace What:="=", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
' SELECIONA A COLUNA A E SUBSTITUI . POR VAZIO
Columns("A:A").Select
Selection.Replace What:=".", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range("I1").Select
' INSERINDO FÓRMULA PARA MANTER APENAS LINHA COM NÚMEROS, OU SEJA, LINHAS QUE CONTEM CONTAS
Range("I1").Select
ActiveCell.FormulaR1C1 = "=IF(ISNUMBER(RC[-8])=TRUE,""OK"",NA())"
' COPIANDO A FÓRMULA PARA AS DEMAIS LINHAS, EXCLUINDO AS CÉLULAS CUJO RESULTADO É IGUAL A NÃO DISPONÍVEL
Application.Goto Reference:="R100000C1"
Selection.End(xlUp).Select
ActiveCell.Offset(0, 8).Range("A1").Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
Selection.SpecialCells(xlCellTypeFormulas, 16).Select
Selection.EntireRow.Delete
Columns("I:I").Select
Selection.Delete Shift:=xlToLeft
' RECOMPONDO O CABEÇALHO, ANTERIORMENTE EXCLUIDO PELA FÓRMULA
' INSERINDO UMA LINHA
Rows("1:1").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A1") = "Conta"
Range("B1") = "Descrição"
Range("C1") = "Saldo Inicial"
Range("E1") = "Débito"
Range("F1") = "Crédito"
Range("G1") = "Saldo Final"
Range("A1").Select
' EXCLUINDO A COLUNA C (TIPO)
Columns("D:D").Select
Selection.Delete Shift:=xlToLeft
' FÓRMULA PARA COMPOSIÇÃO DO SALDO
Range("H2").Select
ActiveCell.FormulaR1C1 = _
"=IF(AND(LEFT(RC[-7],1)=""1"",RC[-1]=""C""),-RC[-2],IF(AND(LEFT(RC[-7],1)=""2"",RC[-1]<>""C""),-RC[-2],IF(AND(LEFT(RC[-7],1)=""3"",RC[-1]<>""C""),-RC[-2],IF(AND(LEFT(RC[-7],1)=""4"",RC[-1]<>""C""),-RC[-2],RC[-2]))))"
Range("I2").Select
ActiveCell.FormulaR1C1 = _
"=IF(AND(LEFT(RC[-8],1)=""1"",RC[-2]=""C""),-(RC[-5]-RC[-4]),IF(AND(LEFT(RC[-8],1)=""2"",RC[-2]<>""C""),-(RC[-5]-RC[-4]),IF(AND(LEFT(RC[-8],1)=""3"",RC[-2]<>""C""),-(RC[-5]-RC[-4]),IF(AND(LEFT(RC[-8],1)=""4"",RC[-2]<>""C""),-(RC[-5]-RC[-4]),RC[-4]-RC[-5]))))"
' COPIANDO AS FÓRMULAS PARA AS DEMAIS LINHAS
Application.Goto Reference:="R100000C1"
Selection.End(xlUp).Select
ActiveCell.Offset(0, 7).Range("A1").Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
Application.Goto Reference:="R100000C1"
Selection.End(xlUp).Select
ActiveCell.Offset(0, 8).Range("A1").Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
' COPIANDO AS FÓRMULAS COMO VALOR
Columns("H:I").Select
Range("H2").Activate
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
' EXCLUINDO A COLUNA DO TIPO
Columns("G:G").Select
Range("G2").Activate
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
' AJUSTANDO AS COLUNAS
Cells.Select
Cells.EntireColumn.AutoFit
Range("A1").Select
' TITULO DAS NOVAS COLUNAS DE SALDO
Range("G1") = "Final Contábil"
Range("H1") = "Mês Contábil"
' INSERINDO COLUNA COM O PERÍODO
Columns("A:A").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Columns("B:B").Select
Selection.Copy
Columns("A:A").Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Range("A1").Select
ActiveCell.FormulaR1C1 = "Período"
Range("A2") = DataBal
' COPIANDO O PERÍODO PARA AS DEMAIS LINHAS
Application.Goto Reference:="R100000C2"
Selection.End(xlUp).Select
ActiveCell.Offset(0, -1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
Columns("A:A").Select
Range("A2").Activate
Selection.NumberFormat = "mm/yy"
' ALTERANDO NOME DA PLANILHA
ActiveSheet.Name = "Balancete"
' SALVANDO O ARQUIVO COMO ARQUIVO TEMPORÁRIO
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:= _
"R:\Governança Corporativa\Base_Balancete\Bal_Tecglas\Bal_Temp_Tec.xls", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
' FORMATAR O DOCUMENTO, CONFIGURAR PÁGINA PARA IMPRESSÃO
Range("A1:I1").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Selection.Font.Bold = True
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.PatternTintAndShade = 0
End With
With Selection.Font
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
End With
Columns("A:A").Select
With Selection
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Columns("D:I").Select
Selection.Style = "Comma"
Cells.Select
Cells.EntireColumn.AutoFit
Range("A1").Select
Selection.CurrentRegion.Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
ActiveWindow.DisplayGridlines = False
Range("A1").Select
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
ActiveWindow.FreezePanes = True
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.PrintTitleRows = "$1:$1"
.PrintTitleColumns = ""
End With
Application.PrintCommunication = True
ActiveSheet.PageSetup.PrintArea = ""
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = ""
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
.LeftMargin = Application.InchesToPoints(0)
.RightMargin = Application.InchesToPoints(0)
.TopMargin = Application.InchesToPoints(0.196850393700787)
.BottomMargin = Application.InchesToPoints(0.196850393700787)
.HeaderMargin = Application.InchesToPoints(0.511811023622047)
.FooterMargin = Application.InchesToPoints(0)
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 600
.CenterHorizontally = True
.CenterVertically = False
.Orientation = xlLandscape
.Draft = False
.PaperSize = xlPaperA4
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = 100
.PrintErrors = xlPrintErrorsDisplayed
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.ScaleWithDocHeaderFooter = True
.AlignMarginsHeaderFooter = True
.EvenPage.LeftHeader.Text = ""
.EvenPage.CenterHeader.Text = ""
.EvenPage.RightHeader.Text = ""
.EvenPage.LeftFooter.Text = ""
.EvenPage.CenterFooter.Text = ""
.EvenPage.RightFooter.Text = ""
.FirstPage.LeftHeader.Text = ""
.FirstPage.CenterHeader.Text = ""
.FirstPage.RightHeader.Text = ""
.FirstPage.LeftFooter.Text = ""
.FirstPage.CenterFooter.Text = ""
.FirstPage.RightFooter.Text = ""
End With
Application.PrintCommunication = True
ActiveWindow.View = xlPageBreakPreview
ActiveWindow.View = xlNormalView
' EXECUTAR SEGUNDA ESTAPA DA MACRO, PARA INCLUIR BALANCETE NA BASE DE MODELOS
Call Alimenta_Modelo_Tec
' INSERIR ANTES DO END SUB
counter = counter + 1
Wend
End Sub
Sub Alimenta_Modelo_Tec()
'ABRIR ARQUIVO MODELO TECGLASS
Application.DisplayAlerts = False
Workbooks.Open Filename:="R:\Governança Corporativa\Base_Modelo\Modelos_TEC.xlsx"
MsgBox DataBal
' VERIFICAR SE A DATA JÁ EXISTE NA BASE DE DADOS
For Each Per In [A2:A1000]
If DataBal = Per Then
MsgBox "O PERÍODO JÁ EXISTE"
Exit For
End If
Next Per
'VOLTAR PARA O BALANCETE
Windows("Bal_Temp_Tec.xls").Activate
'COPIANDO O BALANCETE PARA A BASE DE MODELO
Range("A2").Select
Application.Goto Reference:="R2C1:R1000C9"
Selection.Copy
Windows("Modelos_TEC.xlsx").Activate
Application.Goto Reference:="R100000C1"
Selection.End(xlUp).Select
ActiveCell.Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
' COPIANDO AS FÓRMULAS DE CLASSIFICAÇÃO PARA AS DEMAIS LINHAS
Application.Goto Reference:="R100000C1"
Selection.End(xlUp).Select
ActiveCell.Offset(0, 9).Select
Range(Selection, Selection.End(xlUp)).Select
Application.CutCopyMode = False
Selection.FillDown
Application.Goto Reference:="R100000C1"
Selection.End(xlUp).Select
ActiveCell.Offset(0, 10).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
Application.Goto Reference:="R100000C1"
Selection.End(xlUp).Select
ActiveCell.Offset(0, 11).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
Application.Goto Reference:="R100000C1"
Selection.End(xlUp).Select
ActiveCell.Offset(0, 12).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
Application.Goto Reference:="R100000C1"
Selection.End(xlUp).Select
ActiveCell.Offset(0, 13).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown
' VERIFICAR SE EXISTE ALGUMA FÓRMULA COM ERRO E RETORNAR MENSAGEM
For Each Cell In [J2:N500]
If IsError(Cell) Then
MsgBox "VERIFICAR CONTAS INEXISTENTES, ALIMENTAR ARQUIVO BASE_CLASSIFICA"
Exit For
End If
Next Cell
' IR PARA PLANILHA DRE
Sheets("DRE_TEC_MES").Select
Range("C2") = DataBal
Windows("Bal_Temp_Tec.xls").Close
Form_TEC.Hide
End Sub
Talvez tenha outra forma de fazer essa validação! Se vocês puderem me ajudar!
Desculpe as gambs da macro, mas funciona assim e ganho um tempão com isso!
Abraços e Obrigado