代码之家  ›  专栏  ›  技术社区  ›  Gerry Coll

为什么我不能设置应用程序。替换格式。数字格式化为某些有效格式?

  •  3
  • Gerry Coll  · 技术社区  · 16 年前

    我正试图使用Excel宏重新格式化使用OLE Automation导出的电子表格

    以下代码工作正常:

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

    如果我将ReplaceFormat更改为

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

    为了仅显示1位小数,我得到错误1004(应用程序定义或对象定义错误)。“0.0”也失败了。

    我可以将单元格格式(Cells.NumberFormat)设置为“#,###0.0”

    我只在Excel-2003上尝试过,因为它是我唯一可用的版本。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Gerry Coll    16 年前

    我找到了部分答案。要使其工作,工作簿中必须已经存在NumberFormat。

    解决方法是将单元格的格式设置为“#,##0.0”,然后进行替换:

    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
    

    似乎没有任何集合允许我使用自定义数字格式( According to this site anyway ).

    我在设置应用程序时发现了这一点。FindFormat转换为新格式开始抛出错误!

        2
  •  1
  •   hrvoj3e    9 年前

    运行时错误“1004”:应用程序定义或对象定义错误

    要避免此错误,您必须至少有一次具有两种使用格式的现有单元格。我有列名的第一行,所以它们只有字符串值,将前两个列名设置为dateformat不会对我的工作表数据产生任何明显的影响。

    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
    

    在Excel 2003、2007、2010中工作!