导出的CSV格式问题

时间:2016-02-11 13:57:31

标签: excel vba excel-vba csv

我有一个Macro Man为我创建的宏,它将按范围导出excel表到csv。当我运行宏时,csv的格式不是我想要的。例如,电子表格中的最后一列是货币值(100.25),但是当我转换它时,我得到的值为100.2542。在宏中的任何地方我可以插入一个命令,允许我更正格式或将格式更改为正确的格式吗?感谢您提前提供任何帮助。

 Sub MacroMan()

ChDrive "P:" '// <~~ change current drive to P:\
Dim copyRng As Excel.Range
Dim ThisWB  As Excel.Workbook
Dim OtherWB As Excel.Workbook
Dim sName   As String

'// set reference to the 'Master' workbook
Set ThisWB = ActiveWorkbook

'// assign selected range to 'copyRng'
Set copyRng = Application.InputBox(Prompt:="Select range to convert   to         CSV", Type:=8)

'// If the user selected a range, then proceed with rest of code:
 If Not copyRng Is Nothing Then
'// Create a new workbook with 1 sheet.
Set OtherWB = Workbooks.Add(1)

'// Get A1, then expand this 'selection' to the same size as copyRng. 
'// Then assign the value of copyRng to this area (similar to copy/paste)
OtherWB.Sheets(1).Range("A1").Resize(copyRng.Rows.Count,                  copyRng.Columns.Count).Value = copyRng.Value

'// Get save name for CSV file.
sName = Application.GetSaveAsFilename(FileFilter:="CSV files (*.csv),    *.csv")

'// If the user entered a save name then proceed:
If Not LCase(sName) = "false" Then
    '// Turn off alerts
    Application.DisplayAlerts = False
    '// Save the 'copy' workbook as a CSV file
    OtherWB.SaveAs sName, xlCSV
    '// Close the 'copy' workbook
    OtherWB.Close
    '// Turn alerts back on
    Application.DisplayAlerts = True
End If

'// Make the 'Master' workbook the active workbook again
ThisWB.Activate

MsgBox "Conversion complete", vbInformation

结束如果

End Sub

1 个答案:

答案 0 :(得分:1)

我个人不推荐这个动作。当显示到两个小数位时,货币通常存储并计算到四个小数位。这是为了确保税收计算的准确性,乘以表示为混合数的数量,以及复杂公式中的长列数的总和。将值截断为小数点后两位将不可避免地让您失去一分钱&#39;某处。

据说,这就是你想要做的,这就是你如何做到的。

'// If the user entered a save name then proceed:
If Not LCase(sName) = "false" Then
    '// Turn off alerts
    Application.DisplayAlerts = False
    ' set Precision As Displayed' - permanently truncates off numbers to the displayed decimal places
    OtherWB.PrecisionAsDisplayed = True
    '// Save the 'copy' workbook as a CSV file
    OtherWB.SaveAs sName, xlCSV
    ' turn off Precision As Displayed' - numbers have been permanently changed; you don't get back the lost decimal places
    OtherWB.PrecisionAsDisplayed = False
    '// Close the 'copy' workbook
    OtherWB.Close
    '// Turn alerts back on
    Application.DisplayAlerts = True
End If