Excel宏将日期值转换为纯文本,无格式

时间:2014-03-13 15:00:18

标签: excel excel-vba vba

this one类似的问题(但不一样)。

我的问题略有不同。我有一列日期从mm/dd/yyyy转换为yyyy-mm-dd。例如:

  

2013年11月4日
  2013年11月5日
  二〇一三年十二月十日

这些单元格的格式如下:yyyy-mm-dd

我遇到符合XML Schema的问题,然后导出到XML。我认为这个问题与细胞公式有关(当没有公式时似乎有效),因此我只想保留文本并删除格式。

有一个Clear > Clear Formats选项,但会将日期转换回原始状态mm/dd/yyyy

我还需要在宏中执行此操作。

这是我的伪代码:

For Each cell In myRange
    Dim s As String
    s = c.Text
    c.ClearFormats
    c.Text = s
Next

我认为这样可行,但它没有...我收到object required错误消息。

2 个答案:

答案 0 :(得分:2)

这至少是正确的语法:

Sub demo()
    Dim Myrange As Range, Cell As Range
    Dim s As String
    Set Myrange = Range("A1:A10")
    For Each Cell In Myrange
        s = Cell.Text
        Cell.ClearFormats
        Cell.Value = s
    Next Cell
End Sub

但您可能实际需要

Sub demo()
    Dim Myrange As Range, Cell As Range
    Dim s As String
    Set Myrange = Range("A1:A10")
    For Each Cell In Myrange
        s = Cell.Text
        Cell.NumberFormat = "@"
        Cell.Value = s
    Next Cell
End Sub

答案 1 :(得分:0)

在下面

做一点点狡猾
For Each Cell In myrange
    Dim s As String
    s = "'" & Cell.Text
    Cell.ClearFormats
    Cell.Value = s
Next