Use of .NumberFormat to Format Decimal Places in Excel VBA

扶醉桌前 提交于 2020-05-13 02:44:07

问题


I am inserting data into a Word doc from an Excel spreadsheet. There is a value that has more than 2 decimal places. I am using the following code to try to convert it to 2 decimal places and paste it to my doc.

 wdApp.Selection.GoTo what:=-1, Name:="Device_Avail"
''Referring to the total count column in the Device Availability worksheet.
Set devAvailRow = shDevAvail.Range("A:A").Find("Overall Totals:",       
After:=Cells(1, 1), searchdirection:=xlPrevious)

''Actual piece to format value to 2 decimal places.
shDevAvail.Cells(devAvailRow.Row, 3).NumberFormat = "0.00"
devAvailPer = shDevAvail.Cells(devAvailRow.Row, 3)
wdApp.Selection.TypeText devAvailPer

The value now shows only 2 decimal places, but the formula bar is showing a lot more.

And ?Selection.Value in the Immediate Window of VBA console is showing 89.43448051 too. And this gets pasted into my doc.

Why can the .NumberFormat function change it to 2 decimal places? What do I need to change?


回答1:


The .NumberFormat property formats the rendered text and doesn't alter the value stored in the cell. You can use 'Range.Text' to get the displayed value:

Range("A1") = 99.12345
Range("A1").NumberFormat = "0.00"
Debug.Print Range("A1").Text   '  > 99.12
Debug.Print Range("A1").Value  '  > 99.12345



回答2:


Number format only changes the format that you see. The underlying value is VARIANT anyways. Try using ROUND() function in order to make sure you import only 2 decimal places




回答3:


Why can the .NumberFormat function change it to 2 decimal places? What do I need to change?

Generally speaking you really do not want to change the precision of the raw underlying value. When you do, the 'lost-a-penny' scenario often comes into play; particularly so when calculating and totalling percentages in taxes, interest rates, wholesale-to-retail markup, etc.

With that said, you can quickly change precision of the underlying value to what is displayed for the entire workbook with the following.

ActiveWorkbook.PrecisionAsDisplayed = True

The .PrecisionAsDisplayed property is a member of the Workbook Object. As such it can be accessed with the ActiveWorkbook property, ThisWorkbook Property or a named workbook in the Workbooks Collection.

Warning! This action cannot be undone. Once you truncate the decimal precision to the displayed value, you cannot get it back.

This option is also available within Excel Options, Advanced, When calculating this workbook, Set Precision as displayed. Expect a similar warning.



来源:https://stackoverflow.com/questions/36878519/use-of-numberformat-to-format-decimal-places-in-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!