Skip to content

Instantly share code, notes, and snippets.

@mateusalxd
Last active February 15, 2022 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mateusalxd/bd37e1597af39d2bbda92e16de9cd8a7 to your computer and use it in GitHub Desktop.
Save mateusalxd/bd37e1597af39d2bbda92e16de9cd8a7 to your computer and use it in GitHub Desktop.
VBA - Criar planilha com numeração automática
Sub CriarNovaPlanilha()
' declara as variáveis
Dim ultimaPlanilha As Integer
Dim planilhaVerificada As Integer
Dim nomePlanilha As String
Dim padraoNomePlanilha As String
Dim posicaoInicio As Integer
' define o nome da planilha
nomePlanilha = "VT"
' define o padrão de texto referente ao nome da planilha
padraoNomePlanilha = nomePlanilha & " (*)"
' define a última planilha com "nomePlanilha" encontrada,
' o 0 (zero) indica que ainda não foi encontrada
ultimaPlanilha = 0
' desativa atualização de tela
Application.ScreenUpdating = False
' adiciona nova planilha no final
Sheets.Add After:=Sheets(Sheets.Count)
' percorre todas as planilhas existentes
For i = 1 To Sheets.Count Step 1
' verifica os nomes das planilhas
If Sheets(i).Name = nomePlanilha And ultimaPlanilha = 0 Then
' define que foi encontrada uma planilha com o nomePlanilha
ultimaPlanilha = 1
ElseIf Sheets(i).Name Like padraoNomePlanilha Then
' define posição de início, considerando o total de caracteres do "nomePlanilha",
' um espaço, um parenteses e a posição do primeiro número, por isso do 3
posicaoInicio = Len(nomePlanilha) + 3
' pega o número que está entre os parênteses
planilhaVerificada = CInt(Mid(Sheets(i).Name, posicaoInicio, Len(Sheets(i).Name) - posicaoInicio))
' verifica o número da planilha atual com o número da última encontrada
If planilhaVerificada > ultimaPlanilha Then
' define o número da última planilha encontrada
ultimaPlanilha = planilhaVerificada
End If
End If
Next i
' seleciona a planiha atual
Sheets(Sheets.Count).Select
' verifica qual o nome deverá ser considerado
If ultimaPlanilha = 0 Then
Sheets(Sheets.Count).Name = nomePlanilha
Else
Sheets(Sheets.Count).Name = nomePlanilha & " (" & CStr(ultimaPlanilha + 1) & ")"
End If
' ativa atualização de tela
Application.ScreenUpdating = True
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment