Excel VBA 十进制数在文本输出中转换为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14486680/
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 decimal numbers get converted to integers in text output
提问by marillion
I have a spreadsheet, and I have written a macro which uses some of the values in the spreadsheet to output a text file. Everything works fine except one issue:
我有一个电子表格,我编写了一个宏,它使用电子表格中的一些值来输出一个文本文件。除了一个问题外,一切正常:
If I have a floating number like 15.0, it shows up in the output text file as integer 15, without the decimal point. I do not observe the same issue if the number after the decimal point is something other than zero, e.g., 15.1 gets written as 15.1; no problem there.
如果我有一个像 15.0 这样的浮点数,它在输出文本文件中显示为整数 15,没有小数点。如果小数点后的数字不是零,我不会观察到同样的问题,例如,15.1 被写为 15.1;没问题。
I wonder if there is some kind of a command or property, which would force all numbers are written to the output file as floating numbers?
我想知道是否有某种命令或属性会强制将所有数字作为浮点数写入输出文件?
This is the line I write the numbers to the text file. WeightList(i) and SpacingList(i) are string arrays, which are used for storing the numbers collected from the spreadsheet.
这是我将数字写入文本文件的行。WeightList(i) 和 SpacingList(i) 是字符串数组,用于存储从电子表格中收集的数字。
Print #1, Chr(9); "<truck axleW=" & Chr(34) & _
WeightList(i) & Chr(34) & " axleS=" & _
Chr(34) & SpacingList(i) & Chr(34) & "></truck>"
Thank you!
谢谢!
EDIT: This is the line where the numbers are converted to strings, I tried using the format command but this did not help:
编辑:这是将数字转换为字符串的行,我尝试使用 format 命令,但这没有帮助:
WeightList(i) = Format("0.0", Truck(i).AxleWeights(i))
EDIT2: The code works now, after changing the order of the arguments in the format command. Please see the accepted answer for details.
EDIT2:在更改格式命令中参数的顺序后,代码现在可以工作了。有关详细信息,请参阅已接受的答案。
回答by Floris
You can use format(value,"0.0")
to convert to a string with the desired sig figs.
您可以使用format(value,"0.0")
转换为具有所需 sig figs 的字符串。
EDIT - sorry had order reversed...
编辑 - 对不起,订单颠倒了......
回答by Richard Schneider
How about the using FormatNumber
使用情况如何 FormatNumber
FormatNumber(value, 1)
See http://msdn.microsoft.com/en-us/library/xfta99yt(v=vs.80).aspx
请参阅http://msdn.microsoft.com/en-us/library/xfta99yt(v=vs.80).aspx