每个范围的VBA数字格式不同

时间:2017-10-19 14:52:34

标签: excel vba excel-vba decimal number-formatting

我想根据第二个单元格中的小数位数来更改范围的格式。任何的想法? 我使用以下函数来计算小数(作品)

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

当然我知道&#34; CountDecimalPlaces(Cells(2,b))x 0&#34;没有用,但我希望你帮助

让它变得可以理解

2 个答案:

答案 0 :(得分:2)

用以下代码替换您的代码:

Range(cells(3,b),cells(50,b)).NumberFormat = "0." & String(CountDecimalPlaces(Cells(2, b)), "0")

String有两个强制性参数:

  • Number:角色必须重复的次数

  • Character:必须重复的角色

这是另一种可以计算数字中小数位数的方法:

Function CountDecimalPlaces(aNumber As Double) As Long
    CountDecimalPlaces = Len(Split(CStr(aNumber), ".")(1))
End Function

修改(根据Excelosaurus的建议):

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

答案 1 :(得分:0)

你也可以修改你的计数小数。

 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

并在您的主要功能中使用:

 Range(cells(3,b),cells(50,b)).NumberFormat = CountDecimalPlaces (Cells(2, b))