2017-10-19 10 views
0

2番目のセルからの小数点以下の桁数に従って、範囲の書式を変更したいとします。何か案が?私はVBA番号範囲ごとに異なる書式設定

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を知っている小数の異なる量で私の範囲をフォーマットするためにこれを使用したいと思います 細胞(2は、B))は0" のdoesnのtの仕事をxは、私はあなたが

答えて

2

これであなたのコードを置き換え支援するために、それが理解できるよう願っています:

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

Stringは、2つの必須の引数取ります

  • 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 
+2

提案機能は、全体の数字のためにと小数点区切りとしてピリオドよりも何か他のものを使用しているシステム上で失敗します。 Application.International(xlDecimalSeparator)を使用します。 – Excelosaurus

+0

@Excelosaurus、それを指摘してくれてありがとう。私は投稿した機能を変更しました。 – Mahesh

+1

これは、フォーマットのために0または1を返します。あなたがきれいなライナーにこれを詰め込むとは思わない:-)私はラウンド(aNumber、0)= aNumber Then CountDecimalPlaces = 0 Else CountDecimalPlaces = Len(分割(CStr(aNumber)、Application)。国際(xlDecimalSeparator)、比較:= vbBinaryCompare)(1)))終了します。 – Excelosaurus

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)) 
関連する問題