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

人盡茶涼 提交于 2020-01-03 19:23:12

问题


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.


回答1:


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!




回答2:


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!



来源:https://stackoverflow.com/questions/459524/why-cant-i-set-application-replaceformat-numberformat-to-some-valid-formats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!