问题
I would like Excel VBA to write either a number or a percentage, depending upon a user control.
In Excel, I can hit Ctrl 1 to apply a custom format such as "Text:" 0.0% or "Text:" 0.0.
I have managed to write the text and then use either Format() or Round(), depending upon the control value. However, Format has two decimal places, and I would like a single decimal place.
Here is some illustrative code. As stated above, I would like to have control over the number of decimal places for the percentages (e.g. 0, 1, 2).
Select Case sControl
Case "Percentage"
oRange = "Text: " & Format(dvalue + 0.000001, "Percent")
Case "Numeric"
oRange = "Text: " & Round(dvalue + 0.000001, 1)
End Select
Any pointers on how to do this would be great. I am adding 0.000001 to dvalue in both cases, as I understand that this helps to maintain traditional rounding accuracy.
Cheers Tim
回答1:
I think this is what you are looking for:
FormatPercent(1 + 0.000001, 1)
It formats as a percentage and the second argument (the 1 in this case) is the number of decimal points you want.
This is where I found it.
This is a very good resource for the Format function too.
回答2:
How this is done is by changing the Range.Style
and/or the Range.NumberFormat
property for a given Range
.
For example: Selection.NumberFormat = "0.00000%"
In general how to get to know this in Excel-VBA is simply by recording a macro where you do exactly what you want to happen in your macro. Stop recording, go to the VBA window and look at the new macro in one of the Module1, Module2, ... modules.
You don't actually need to round the numbers to get the formatting that you want, just as you wouldn't need to when you apply number formatting manually in your sheets.
来源:https://stackoverflow.com/questions/16302795/how-do-i-apply-a-custom-format-such-as-text-0-0-in-excel-vba