vba 保存为文本时使用逗号代替小数点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22804699/
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:37:56  来源:igfitidea点击:

Use comma instead of dot for decimals when saving as text

excelvbaexcel-vbanumber-formatting

提问by Lee White

This question looks similar to Visual basic handle decimal comma, but that one is about an entirely different problem.

这个问题看起来类似于Visual basic 处理十进制逗号,但这是一个完全不同的问题。

I am writing a VBA macro to save my Excel file to a .txtfile. This code line was generated by actually recording a macro where I saved the file to .txt:

我正在编写一个 VBA 宏来将我的 Excel 文件保存到一个.txt文件中。此代码行是通过实际录制我将文件保存到的宏生成的.txt

ActiveWorkbook.SaveAs Filename, FileFormat:=xlText

Now, the issue is that the .txtfile has all decimals formatted with dots, while I require them to be commas. For instance, it writes 32.7while I am expecting 32,7.

现在,问题是该.txt文件的所有小数都用点格式化,而我要求它们是逗号。例如,它32.7在我期待32,7.

Some interesting details:

一些有趣的细节:

  • I have made sure that Windows and Excel are setup to use the correct local settings. Everywhere I look, decimals are displayed correctly with commas.
  • When manually saving the workbook, it correctly writes commas to the file as well. However, when executing the VBA code I recorded when doing this, I get dots.
  • 我已确保 Windows 和 Excel 已设置为使用正确的本地设置。无论我在哪里,小数都用逗号正确显示。
  • 手动保存工作簿时,它也会正确地将逗号写入文件。但是,在执行我在执行此操作时记录的 VBA 代码时,我得到了点。

Is there some nifty argument or option that I forgot? I am truly at a loss here -- even my fourth cup of coffee is not bringing any inspiration.

是否有一些我忘记的漂亮论点或选项?我真的很茫然——即使我的第四杯咖啡也没有带来任何灵感。

回答by Dmitry Pavliv

This works for me (if your local separator is comma):

这对我有用(如果您的本地分隔符是逗号):

ActiveWorkbook.SaveAs Filename, FileFormat:=xlText, Local:=True

You can also specify any separator you want explicitly:

您还可以明确指定任何您想要的分隔符:

Application.DecimalSeparator = "," ' or any other separator, e.g. "-"
ActiveWorkbook.SaveAs Filename, FileFormat:=xlText, Local:=True

but it affects entire workbook, you can then change it back after saving txt file, if it differs from your local separator

但它会影响整个工作簿,如果它与本地分隔符不同,您可以在保存 txt 文件后将其更改回来