每个范围VBA Numberformat不同
我想根据第二个单元格的小数位数来改变我的范围的格式。 任何想法? 我使用下面的函数来计算小数(作品)
Function CountDecimalPlaces(aNumber As Double) As Long Dim len1 As Long, len2 As Long len1 = Len(CStr(aNumber)) len2 = Len(CStr(Int(aNumber))) CountDecimalPlaces = len1 - len2 + CLng(len1 <> len2) End Function
并想使用这个来设置我的范围不同的小数位数
For b = 1 To lastCol Range(cells(3,b),cells(50,b)).NumberFormat = "0." & CountDecimalPlaces (Cells(2, b)) x 0 Next b
当然我知道“CountDecimalPlaces(Cells(2,b))x 0”不起作用,但我希望它能让你理解
用这个代替你的代码:
Range(cells(3,b),cells(50,b)).NumberFormat = "0." & String(CountDecimalPlaces(Cells(2, b)), "0")
该String
有两个强制参数:
-
Number
:一个angular色必须重复的次数 -
Character
:必须重复的angular色
这里有另一种方法可以计算一个数字中的小数位数:
Function CountDecimalPlaces(aNumber As Double) As Long CountDecimalPlaces = Len(Split(CStr(aNumber), ".")(1)) End Function
编辑 (基于Excelosaurus的build议):
Function CountDecimalPlaces(aNumber As Double) As Long If Int(aNumber) = aNumber Then CountDecimalPlaces = 0 Else CountDecimalPlaces = Len(Split(CStr(aNumber), Application.International(xlDecimalSeparator))(1)) End If End Function
您也可以修改您的计数小数点。
Function CountDecimalPlaces(aNumber As Double) As String Dim len1 As Long, len2, lenX As Long Dim i As Integer Dim answer As String answer = "0." len1 = Len(CStr(aNumber)) len2 = Len(CStr(Int(aNumber))) lenX = len1 - len2 + CLng(len1 <> len2) If lenX > 0 Then For i = 1 To lenX answer = answer & "0" Next i End If CountDecimalPlaces = answer End Function
并使用你的主要function是这样的:
Range(cells(3,b),cells(50,b)).NumberFormat = CountDecimalPlaces (Cells(2, b))