
Tópico Oficial Dicas de Excel
__________________________________________
Envie MP para sugerir tópicos para esta seção.

__________________________________________
Sala destinada para questões, dúvidas e dicas envolvendo pacotes ou suítes de escritório destinados ao Windows: instalação, configuração, desempenho, implementações, suítes Office, Open Office, Libre Office etc.
Sub lsUnificarPlanilhas()
On Error GoTo Sair
Dim lUltimaColunaAtiva As Long
Dim lUltimaLinhaAtiva As Long
Dim lRng As Range
Dim sPath As String
Dim fName As String
Dim lNomeWB As String
Dim lIPlan As Integer
Dim lUltimaLinhaPlanDestino As Long
PlanilhaDestino = ThisWorkbook.Name
sPath = Localizar_Caminho
sName = Dir(sPath & "\*.xl*"
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Do While sName <> ""
fName = sPath & "\" & sName
Workbooks.Open Filename:=fName, UpdateLinks:=False
lNomeWB = ActiveWorkbook.Name
For lIPlan = 1 To ActiveWorkbook.Sheets.Count
Workbooks(lNomeWB).Worksheets(lIPlan).Activate
lUltimaLinhaAtiva = Cells(Rows.Count, 1).End(xlUp).Row
lUltimaColunaAtiva = ActiveSheet.Cells(1, 5000).End(xlToLeft).Column
Set lRng = Range(Cells(1, lUltimaColunaAtiva).Address)
Range("A" & 1 & ":" & gfLetraColuna(lRng) & lUltimaLinhaAtiva).Select
Selection.Copy
Workbooks(PlanilhaDestino).Worksheets(1).Activate
lUltimaLinhaPlanDestino = Cells(Rows.Count, 1).End(xlUp).Row
If lUltimaLinhaPlanDestino > 1 Then
lUltimaLinhaPlanDestino = Cells(Rows.Count, 1).End(xlUp).Row + 1
End If
Range("A" & lUltimaLinhaPlanDestino).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Next lIPlan
Workbooks(lNomeWB).Close SaveChanges:=False
sName = Dir()
Loop
MsgBox "Planilhas unificadas!"
Sair:
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
End Sub
Function gfLetraColuna(ByVal rng As Range) As String
Dim lTexto() As String
lTexto = Split(rng.Address, "$"
gfLetraColuna = lTexto(1)
End Function
Public Function Localizar_Caminho() As String
Dim strCaminho As String
With Application.FileDialog(msoFileDialogFolderPicker)
'Permitir mais de uma pasta
.AllowMultiSelect = False
'Mostrar janela
.Show
If .SelectedItems.Count > 0 Then
strCaminho = .SelectedItems(1)
End If
End With
'Atribuir caminho a variável
Localizar_Caminho = strCaminho
End Function
Sub CopyAndSaveExcelFiles()
Dim folderPath As String
Dim templateFile As String
Dim sourceFile As String
Dim filePattern As String
Dim templateWB As Workbook
Dim sourceWB As Workbook
Dim newEnding As String
Dim newFileName As String
Dim destFile As String
Dim sourceSheet As Worksheet
Dim copiedSheet As Worksheet
Dim sheetNewName As String
Dim attemptToCopy As Boolean
On Error GoTo ErrorHandler ' Controle de erros
folderPath = "C:\Nova pasta (2)\Conciliações BR\"
templateFile = Dir(folderPath & "Reconciliation Template*.xlsb", vbNormal)
If templateFile <> "" Then
Set templateWB = Workbooks.Open(folderPath & templateFile, UpdateLinks:=False)
newEnding = templateWB.Sheets(1).Range("B3".Value
Else
MsgBox "Arquivo de template não encontrado.", vbExclamation
Exit Sub
End If
filePattern = "*.xlsb"
sourceFile = Dir(folderPath & filePattern, vbNormal)
Do While sourceFile <> ""
If sourceFile <> templateFile Then
Set sourceWB = Workbooks.Open(folderPath & sourceFile, UpdateLinks:=False)
For Each sourceSheet In sourceWB.Worksheets
attemptToCopy = False
sheetNewName = sourceSheet.Name
' Verificar se a planilha está protegida
If sourceSheet.ProtectContents Then
MsgBox "A planilha " & sourceSheet.Name & " está protegida. Desproteja antes de copiar.", vbExclamation
Else
' Tentar copiar a planilha e verificar a falha
On Error Resume Next
sourceSheet.Copy After:=templateWB.Sheets(templateWB.Sheets.Count)
If Err.Number = 0 Then
Set copiedSheet = templateWB.Sheets(templateWB.Sheets.Count)
attemptToCopy = True
End If
On Error GoTo 0
If attemptToCopy Then
' Verifica se o nome já existe e renomeia se necessário
If IsSheetNameExists(templateWB, sheetNewName) Then
sheetNewName = GenerateUniqueSheetName(templateWB, sheetNewName)
End If
copiedSheet.Name = sheetNewName
Set copiedSheet = Nothing
Else
MsgBox "Falha ao copiar a planilha: " & sourceSheet.Name, vbExclamation
End If
End If
Next sourceSheet
newFileName = Left(sourceFile, InStrRev(sourceFile, "." - 1) & "_" & newEnding & ".xlsb"
destFile = folderPath & newFileName
templateWB.SaveAs destFile, FileFormat:=50
sourceWB.Close SaveChanges:=False
End If
sourceFile = Dir()
Loop
templateWB.Close SaveChanges:=False
MsgBox "Processo concluído com sucesso!", vbInformation
Exit Sub
ErrorHandler:
MsgBox "Ocorreu um erro: " & Err.Description, vbExclamation
If Not sourceWB Is Nothing Then sourceWB.Close SaveChanges:=False
If Not templateWB Is Nothing Then templateWB.Close SaveChanges:=False
End Sub
Function IsSheetNameExists(ByVal wb As Workbook, ByVal sheetName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = wb.Sheets(sheetName)
IsSheetNameExists = Not ws Is Nothing
On Error GoTo 0
End Function
Function GenerateUniqueSheetName(ByVal wb As Workbook, ByVal baseName As String) As String
Dim num As Integer
Dim newName As String
num = 1
newName = baseName
Do While IsSheetNameExists(wb, newName)
num = num + 1
newName = baseName & "_" & num
Loop
GenerateUniqueSheetName = newName
End Function