Coverting YYYYMMDD to dd/mm/yyyy ignoring cells with 0 value

YasSheikh

New Member
Joined
Dec 19, 2021
Messages
5
Office Version
  1. 2016
Platform
  1. Windows
Hi all

VBA novice here. I am trying to write a VBA code to convert YYYYMMDD to dd/mm/yyyy format however my range has some 0 values. I have tried writing the below code based on other threads on the board however I keep getting an error "Type mismatch".

I am essentially trying to 'hide' the 0 values and converting all others to dd/mm/yyyy date format. Any help would be greatly appreciated!
VBA Code:
Dim c As Range
    Application.ScreenUpdating = False
    For Each c In Range("H2:H" & Cells(Rows.Count, "H").End(xlUp).Row)
    If c.Value = 0 Then c.NumberFormat = "#;#;" Else
        c.Value = DateSerial(Left(c.Value, 4), Mid(c.Value, 5, 2), Right(c.Value, 2))
        c.NumberFormat = "dd/mm/yyyy"
    Next
    Application.ScreenUpdating = False
Cheers!
 
Last edited by a moderator:

Excel Facts

Best way to learn Power Query?
Read M is for (Data) Monkey book by Ken Puls and Miguel Escobar. It is the complete guide to Power Query.

RoryA

MrExcel MVP, Moderator
Joined
May 2, 2008
Messages
39,339
Office Version
  1. 365
  2. 2019
  3. 2016
  4. 2010
Platform
  1. Windows
  2. MacOS
That is not the correct structure for your If block. You need:

VBA Code:
    For Each c In Range("H2:H" & Cells(Rows.Count, "H").End(xlUp).Row)
      If c.Value = 0 Then
         c.NumberFormat = "#;#;"
      Else
         c.Value = DateSerial(Left(c.Value, 4), Mid(c.Value, 5, 2), Right(c.Value, 2))
         c.NumberFormat = "dd/mm/yyyy"
      End If
    Next
 
Solution

RoryA

MrExcel MVP, Moderator
Joined
May 2, 2008
Messages
39,339
Office Version
  1. 365
  2. 2019
  3. 2016
  4. 2010
Platform
  1. Windows
  2. MacOS
Glad we could help. :)
 

Forum statistics

Threads
1,176,025
Messages
5,900,962
Members
434,861
Latest member
Coffee_in_a_jiffy

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top