将 excel 导出到 csv 时如何确保点作为小数点分隔符?

How to ensure dot as decimal separator when exporting excel to csv?

我想通过 vba 从 excel 导出一些数据到 csv 文件,并将小数点分隔符设置为 (独立于本地语言或系统设置)。

现在我已经在 excel 文件中有了数据,并用点作为小数点分隔符。它在某些系统上运行良好,但在其他系统上(例如瑞典系统设置),小数分隔符在通过 excel vba.

导出到 csv 后显示为逗号

这是我目前的相关代码片段:

' Set Export Parameters
Application.DecimalSeparator = "."
Application.ThousandsSeparator = ""
Application.UseSystemSeparators = False
ActiveSheet.Range("D4:G1048571").NumberFormat = "0.00"

' Open (new) output file
Open fileSaveName For Output As #1

' Write date upfront
Print #1, Trim(Worksheets("Output - Upload generator").Range("A2:A2"))

' Set data range for output
Set myrng = Worksheets("Output - Upload generator").Range("A3:G" & lastExportRow)

' Write data
For i = 1 To myrng.Rows.count
    For j = 1 To myrng.Columns.count
        lineText = IIf(j = 1, "", lineText & ";") & myrng.Cells(i, j).Text
    Next j
    Print #1, lineText
Next i

' Close output file
Close #1

到目前为止,在某些系统上使用点作为小数点分隔符可以成功导出,但并非在每个系统上都成功独立于本地设置(例如瑞典语设置 - 小数点分隔符显示为一个逗号)。因为我已经尝试了几件事,比如在 excel 高级设置中更改分隔符,但对每个系统都不起作用。

我很高兴,如果有人能给我提示如何确保点!

我使用的是具有瑞典区域设置的 Excel 的最新官方版本(Office 365,Excel 版本 1812),这对我有用:

Dim myCell As Range    
Set myCell = ActiveSheet.Range("A1")
myCell.Value = CDbl(9999.999)

Application.DecimalSeparator = "."
Application.UseSystemSeparators = False

myCell.NumberFormat = "0.00"
Debug.Print "Cell Value: " & myCell.Value   '9999,999
Debug.Print "Cell Text: " & myCell.Text     '10000.00

我希望以上内容适用于支持此代码的任何 Excel 版本,但如果您需要解决方法,您可以随时这样做:

首先,从Windows区域设置中获取小数点分隔符:

Dim myShell, regDecSep    
Set myShell = CreateObject("WScript.Shell")
regDecSep = myShell.RegRead("HKCU\Control Panel\International\sDecimal")

Debug.Print "System decimal separator: " & regDecSep

然后,在处理工作表时,检查当前单元格中的值是什么类型,如果是数字,则使用Replace函数固定分隔符:

Dim cellText    
cellText = myCell.Text

If regDecSep <> "." Then
    If TypeName(myCell.Value) = "Double" Then
        Debug.Print "Replacing the decimal separator"
        cellText = Replace(cellText, regDecSep, ".")
    End If
End If

Debug.Print "Result: " & cellText

(注意在检查类型时需要使用单元格的Value而不是Text