Home » excel » excel vba – Why can't I set Application.ReplaceFormat.NumberFormat to some valid formats?

excel vba – Why can't I set Application.ReplaceFormat.NumberFormat to some valid formats?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m trying to use an Excel Macro to reformat a spreadsheet exported using OLE-Automation

The following code works OK:

Application.FindFormat.NumberFormat = "#,##0.0000000"
Application.ReplaceFormat.NumberFormat = "#,##0.00"
Cells.Replace What:="", Replacement:="", LookAt:=xlPart, SearchOrder:= _
    xlByRows, MatchCase:=False, SearchFormat:=True, ReplaceFormat:=True

if I change the ReplaceFormat to

Application.ReplaceFormat.NumberFormat = "#,##0.0" 

to display only 1 decimal place, I get an error 1004 (Application-defined or object-defined error). “0.0” fails as well.

I can set the cell format (Cells.NumberFormat) to “#,##0.0”

I have only tried this against Excel-2003 as it is the only version I have available.

How to&Answers:

I have found part of the answer. For this to work, the NumberFormat must already exist in the workbook.

A work-around is to set the format of a cell to “#,##0.0”, then do the replace:

Worksheets("Sheet1").Range("A1").NumberFormat = "#,##0.0" 
Application.FindFormat.NumberFormat = "#,##0.0000000"
Application.ReplaceFormat.NumberFormat = "#,##0.00"
Cells.Replace What:="", Replacement:="", LookAt:=xlPart, SearchOrder:= _
    xlByRows, MatchCase:=False, SearchFormat:=True, ReplaceFormat:=True

There doesn’t seem to be any Collections that allow me to get at the custom number formats (According to this site anyway).

I discovered this when setting Application.FindFormat to a new format started throwing errors!

Answer:

Run-time error ‘1004’: Application-defined or object-defined error

To avoid this error you must have existing cells with both used formats at least once. I have first rows for column names so they have only string values and setting first two column names to dateformat won’t have any visible affect on my sheet data.

Sub datum_popravak_rucno()
    ' add find format to cell A1
    ActiveSheet.Range("A1").NumberFormat = "m/d/yyyy"
    ' add replace format to cell B1
    ActiveSheet.Range("B1").NumberFormat = "yyyy-mm-dd hh:mm:ss"
    ' define find format
    Application.FindFormat.NumberFormat = "m/d/yyyy"
    ' define replace format
    Application.ReplaceFormat.NumberFormat = "yyyy-mm-dd hh:mm:ss"
    ' do replace on all cells
    Cells.Replace What:="", Replacement:="", LookAt:=xlPart, SearchOrder:= _
        xlByColumns, MatchCase:=False, SearchFormat:=True, ReplaceFormat:=True
End Sub

Works in Excel 2003, 2007, 2010!