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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22382649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 02:20:26  来源:igfitidea点击:

Excel Macro to convert date value to plain text, no formatting

excelexcel-vbavba

提问by user3219570

Similar question (but not the same) as this one.

类似的问题(但不相同)这一个

My question is slightly different. I have a column of dates converted from mm/dd/yyyyto yyyy-mm-dd. Ex:

我的问题略有不同。我有一列日期从 转换mm/dd/yyyyyyyy-mm-dd。前任:

2013-11-04
2013-11-05
2013-12-10

2013-11-04
2013-11-05
2013-12-10

These cells are formatted with the following type: yyyy-mm-dd.

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

I'm having an issue conforming to an XML Schema and then exporting to XML. I think the issue is related to the cells formula (seems to work when there is no formula), therefore I'd like to keep the text only and remove the formatting.

我遇到了符合 XML 架构然后导出到 XML 的问题。我认为问题与单元格公式有关(在没有公式时似乎有效),因此我只想保留文本并删除格式。

There is a Clear > Clear Formatsoption but that converts the date back to it's original state mm/dd/yyyy.

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

I also need to do this in a Macro.

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

Here my pseudo code:

这是我的伪代码:

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

I thought this would work but it doesn't... I get an object requirederror message.

我认为这会起作用,但它不起作用...我收到一条object required错误消息。

回答by Gary's Student

This is at least the correct syntax:

这至少是正确的语法:

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

but you might actually need:

但您实际上可能需要

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

回答by Sathish Kothandam

do it with little tricky ..like below

做起来有点棘手..像下面

For Each Cell In myrange
    Dim s As String
    s = "'" & Cell.Text
    Cell.ClearFormats
    Cell.Value = s
Next