Dynamic Decimal Placement

Av8tordude

Well-known Member
Joined
Oct 13, 2007
Messages
743
I using this code that formats the number as I type. I would like to make more dynamic to be able to choose the format base on a variable enter in another textbox. Currently the format is hard coded to two zeros after the decimal. I would like to enter (ex. 3) and the format would show $0.000

Any suggestions?

Thanks


Code:
Dim v As String


Select Case Len(tbOPrice)
    Case 1
        tbOPrice = Format(tbOPrice, "$0\.00")
    Case Is > 1
        v = Replace(tbOPrice, "$", "")
        v = Replace(v, ".", "")
        tbOPrice = Format(CCur(v) / 100, "$#,#0.00")
    Case Else
End Select
 
Last edited:

Special-K99

Well-known Member
Joined
Nov 7, 2006
Messages
8,328
Am no VBA expert, does this work?
You want something along the lines of

Code:
tbOPrice = Format(CCur(v) / 100, "$#,#0." & Right(10 ^ txtbox1,Len(10 ^ txtbox1)-1))
10^txtbox1 : If txtbox1 = 2, result is 100, if txtbox1 is 3 result is 1000
Performing a Right of that calculation using 1 less than the Length of it would knock the first digit off leaving 00 or 000 (I hope)
You can then concatenate that to your decimal "$#,#0."
 
Last edited:

Av8tordude

Well-known Member
Joined
Oct 13, 2007
Messages
743
How do I adjust the codes in red. I have to manually change the numbers in red from 2 zeros to 3 zeros so that it does not cause an error.

Code:
[COLOR=#574123]CCur(v) / [/COLOR][COLOR=#ff0000][B]100[/B][/COLOR]
 
Last edited:

Akuini

Well-known Member
Joined
Feb 1, 2016
Messages
2,476
Office Version
365
Platform
Windows
Untested, but maybe this:

Code:
z = WorksheetFunction.Rept(0, textbox1.Value)
tbOPrice = Format(CCur(V) / 1 & z, "$#,#0." & z)
 

Akuini

Well-known Member
Joined
Feb 1, 2016
Messages
2,476
Office Version
365
Platform
Windows
Hm, let's try this first:

Code:
Sub tryX()

z = WorksheetFunction.Rept(0, 3)
Debug.Print z
Debug.Print 1 & z
Debug.Print "$#,#0." & z

End Sub
The result in immediate window is:
000
1000
$#,#0.000

Isn't that what you expect?
 

Av8tordude

Well-known Member
Joined
Oct 13, 2007
Messages
743
when I type in a value (ex 1),

If the textbox variable is 2, the output should be $1.00
If the textbox variable is 3, the output should be $1.000
 

Akuini

Well-known Member
Joined
Feb 1, 2016
Messages
2,476
Office Version
365
Platform
Windows
If I understand you correctly, maybe this:
Code:
Sub tryA()
x = 1 ' in tbOPrice
y = 3  'in the variable textbox

        V = Replace(x, "$", "")
        V = Replace(V, ".", "")
        z = WorksheetFunction.Rept(0, y)
        x = Format(x, "$#,#0." & z)

Debug.Print x
End Sub
 

Av8tordude

Well-known Member
Joined
Oct 13, 2007
Messages
743
Correct...this is the output I'm looking for. Now the challenge is to implement it into the original code
 

Forum statistics

Threads
1,085,503
Messages
5,384,063
Members
401,878
Latest member
MP_7

Some videos you may like

This Week's Hot Topics

Top