Excel,VBA,使用 numberformat="@" 将数字转换为文本是否有效?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44961293/
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
Excel, VBA, convert number to text with numberformat="@" working or not?
提问by joehua
The basic rule to tell text from number is that text is left-aligned and number is right-aligned.
区分文本和数字的基本规则是文本左对齐,数字右对齐。
In a blank cell, I set the format to text. Then, I entered 25
. This "number" was left-aligned, implying it was text. There was a green triangle on the upper-left corner of the cell with a note saying
在空白单元格中,我将格式设置为text。然后,我进入了25
。这个“数字”是左对齐的,暗示它是文本。单元格左上角有一个绿色三角形,上面写着
"The number in the cell is formatted as text...".
“单元格中的数字格式为文本...”。
So far so good.
到现在为止还挺好。
In the cell right below, I entered 25
. It was right-aligned, implying it was number. I then ran the code Range.NumberFormat="@"
on it. It became left-aligned. However, there was no green triangle.
在下面的单元格中,我输入了25
. 它是右对齐的,暗示它是数字。然后我Range.NumberFormat="@"
在上面运行了代码。它变成了左对齐。但是,没有绿色三角形。
When I used =IF(A1="25",1,0)
to check the first cell, the formula returned 1
. Same test (difference address, of course) on the next cell returned 0
.
当我过去=IF(A1="25",1,0)
检查第一个单元格时,公式返回1
. 下一个单元格上的相同测试(当然是不同的地址)返回0
.
It seems to me the code converted 25
to text (judging from the alignment) and at the same time not converted 25
to text (judging from the lack of a green triangle and the IF
test.)
在我看来,代码转换25
为文本(从对齐方式判断),同时未转换25
为文本(从缺少绿色三角形和IF
测试判断)。
What's going on?
这是怎么回事?
回答by ERT
This may not be the most efficient method, but it works:
这可能不是最有效的方法,但它有效:
Option Explicit
Sub convertText()
Dim testValue As Variant
testValue = ActiveCell.Value & ""
ActiveCell.ClearContents
ActiveCell.NumberFormat = "@"
ActiveCell.Value = testValue
End Sub