Forçar formato data DD/MM/AAAA VBA

andril

03-01-2020 07:43:23

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.

webmaster

03-01-2020 15:33:16

andril

07-01-2020 02:59:29

Opa. Obrigado amigo.

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

andril

07-01-2020 05:54:09

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!

webmaster

07-01-2020 14:11:02

IMG_828225B1314E-1.jpeg