Página 1 de 1

Forçar formato data DD/MM/AAAA VBA

Enviado: Sex Jan 03, 2020 4:43 am
por andril
Bom dia rapazes.

Tenho uma planilha em que insiro datas aleatórias e outros dados para depois imprimir.

O que eu precisava é que, quando digitasse na célula por exemplo "03012020" ele transformasse em "03/01/2020".

Já tentei de tudo e nada. Se deixo a célula formatada para tipo DATA, se eu insiro essa data acima ele retorna erro.

Tenho a fórmula abaixo, que uso para forçar o formato de placa de veículo:

Private Sub Worksheet_SelectionChange(ByVal target As Range)
Dim placa_letra As String
Dim placa_numero As String
For Each x In Range("D4")
If x.Value <> "" And Len(x.Value) = 7 Then
x.Value = UCase(x.Value)
placa_letra = Left(x.Value, 3)
placa_numero = Right(x.Value, 4)
x.Value = placa_letra & "-" & placa_numero
End If
Next
End Sub

Tentei adaptar para o formato data mas não consegui.

Alguém sabe como fazer isso? Muito obrigado.

Re: Forçar formato data DD/MM/AAAA VBA

Enviado: Sex Jan 03, 2020 12:33 pm
por webmaster

Re: Forçar formato data DD/MM/AAAA VBA

Enviado: Seg Jan 06, 2020 11:59 pm
por andril
Opa. Obrigado amigo.

Acompanhei os vídeos e tentei formatar usando a função CDate, mas ainda não consegui acertar :S

Re: Forçar formato data DD/MM/AAAA VBA

Enviado: Ter Jan 07, 2020 2:54 am
por andril
Consegui!

Segue fórmula, só colocar no conteúdo VBA da planilha e escolher o range que no meu caso é apenas a célula C5:

Código: Selecionar todos

Private Sub Worksheet_Change(ByVal Target As Excel.Range)

Dim DateStr As String
On Error GoTo EndMacro
If Intersect(Target, Range("C5")) Is Nothing Then Exit Sub
If Target.Cells.Count > 1 Then Exit Sub
If Target.Value = "" Then Exit Sub

Application.EnableEvents = False
With Target
If .HasFormula = False Then
Select Case Len(.Formula)
Case 4
DateStr = Left(.Formula, 1) & "/" & _
Mid(.Formula, 2, 1) & "/" & Right(.Formula, 2)
Case 5
DateStr = Left(.Formula, 1) & "/" & _
Mid(.Formula, 2, 2) & "/" & Right(.Formula, 2)
Case 6
DateStr = Left(.Formula, 2) & "/" & _
Mid(.Formula, 3, 2) & "/" & Right(.Formula, 2)
Case 7
DateStr = Left(.Formula, 1) & "/" & _
Mid(.Formula, 2, 2) & "/" & Right(.Formula, 4)
Case 8
DateStr = Left(.Formula, 2) & "/" & _
Mid(.Formula, 3, 2) & "/" & Right(.Formula, 4)
Case Else
Err.Raise 0
End Select
.Formula = DateValue(DateStr)
End If
End With
Application.EnableEvents = True
Exit Sub
EndMacro:
MsgBox "Insira: 1120 para 01/01/2020!"
Range(Target.Address).ClearContents
Application.EnableEvents = True
End Sub
Obrigado e até mais!

Re: Forçar formato data DD/MM/AAAA VBA

Enviado: Ter Jan 07, 2020 11:11 am
por webmaster
IMG_828225B1314E-1.jpeg
IMG_828225B1314E-1.jpeg (122.17 KiB) Exibido 2988 vezes