[英]How to change Format of a Cell to Text using VBA
I have a "duration" column in an Excel sheet.我在 Excel 工作表中有一个“持续时间”列。 Its cell format always changes — I want convert the duration from minutes to seconds, but because of the cell formatting it always gives me different answers.
它的单元格格式总是在变化——我想将持续时间从分钟转换为秒,但由于单元格格式,它总是给我不同的答案。
I was thinking that before doing the conversion I could convert that cell format to text so that it will consider that as text value and not try to auto-format it.我在想,在进行转换之前,我可以将该单元格格式转换为文本,以便它会将其视为文本值,而不是尝试自动设置格式。
Currently I am copying all data into Notepad and then saving it back to the Excel sheet to remove all of the previous format.目前我正在将所有数据复制到记事本中,然后将其保存回 Excel 工作表以删除所有以前的格式。 Is there a way to automate setting a cell's formatting to text using VBA?
有没有办法使用 VBA 自动将单元格的格式设置为文本?
To answer your direct question, it is:要回答您的直接问题,它是:
Range("A1").NumberFormat = "@"
Or或者
Cells(1,1).NumberFormat = "@"
However, I suggest changing the format to what you actually want displayed.但是,我建议将格式更改为您实际想要显示的格式。 This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.
这允许您保留单元格中的数据类型并轻松使用单元格公式来操作数据。
One point: you have to set NumberFormat property BEFORE loading the value into the cell.一点:您必须在将值加载到单元格之前设置 NumberFormat 属性。 I had a nine digit number that still displayed as 9.14E+08 when the NumberFormat was set after the cell was loaded.
当加载单元格后设置 NumberFormat 时,我有一个九位数字仍然显示为 9.14E+08。 Setting the property before loading the value made the number appear as I wanted, as straight text.
在加载值之前设置属性使数字显示为我想要的,作为直接文本。
OR:或者:
Could you try an autofit first:您可以先尝试自动调整吗:
Excel_Obj.Columns("A:V").EntireColumn.AutoFit
Well this should change your format to text.那么这应该将您的格式更改为文本。
Worksheets("Sheetname").Activate
Worksheets("SheetName").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select
Selection.NumberFormat = "@"
对于以科学记数法设置格式显示为仅“#”的大数字
To prevent Scientific Notation防止科学记数法
With Range(A:A)
.NumberFormat = "@"
.Value = .Formula
End With
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.