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

How to calculate loan payments in Excel?
Use the PMT function: =PMT(5%/12,60,-25000) is for a $25,000 loan, 5% annual interest, 60 month loan.
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
 
Upvote 0
Solution
Glad we could help. :)
 
Upvote 0

Forum statistics

Threads
1,214,611
Messages
6,120,510
Members
448,967
Latest member
screechyboy79

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
Back
Top