简体   繁体   English

每个范围的VBA Numberformat不同

[英]VBA Numberformat differently for each range

I want to change the format of my ranges according to the number of decimals from the second cell. 我想根据第二个单元格中的小数位数更改范围的格式。 Any idea? 任何想法? I am using the following Function to count Decimals (works) 我正在使用以下函数来计算小数(有效)

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

and would like to use this to format my range with different amount of decimals 并想用它来格式化我的范围以不同的小数位数

For b = 1 To lastCol

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

Next b

Of course I know the "CountDecimalPlaces (Cells(2, b)) x 0" doesn t work but I hope it make it understandable for you to help 当然,我知道“ CountDecimalPlaces(Cells(2,b))x 0”不起作用,但我希望它对您有所帮助

Replace your code with this: 用以下代码替换代码:

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

The String takes two mandatory arguments: String采用两个强制性参数:

  • Number : The number of times a character has to be repeated Number :字符必须重复的次数

  • Character : The character that has to be repeated Character :必须重复的角色

Here's another way you can count the number of decimals in a number: 这是您可以计算数字中小数位数的另一种方法:

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

Edit (based on Excelosaurus' suggestions): 编辑 (基于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

you can modify your counting decimal as below as well. 您也可以按以下方式修改计数小数。

 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

and use in your main function like this : 并像这样在您的主要功能中使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM