PDA

View Full Version : [SOLVED:] Add Roundup formula to VBA button



Ryanchris
10-20-2019, 10:21 PM
Hello!
Newby here looking to add a simple Roundup function in a VBA userform but it appears that this isn't as easy as Excel. I have a simple formula wherein a/b needs to be rounded up no matter what. 112/10=11.2...round up to 12. A and b could be any numbers as they are dependant upon whatever the user enters on the userform. I have a button that says "calculate", that once pressed, needs to run this formula. Please help! Thank you so much in advance!!

大灰狼1976
10-20-2019, 10:28 PM
Hi Ryanchris!
If they are all positive numbers, I usually use the int method like below.
Of course, application.roundup is also correct.

Sub test()
Dim a, b
a = 112
b = 10
'MsgBox Application.RoundUp(a / b, 0)
MsgBox -Int(-a / b)
End Sub

Ryanchris
10-20-2019, 10:32 PM
I will give that a try! I'll let you know how it goes. Thank you!

Artik
10-21-2019, 02:32 AM
And what about the case when b = 0? :devil2:
I only give food for thought.

Artik

大灰狼1976
10-21-2019, 04:55 AM
Hi Artik!
It's going to be a mathematical error not a method error when b = 0.

Ryanchris
10-21-2019, 08:40 AM
Hi Ryanchris!
If they are all positive numbers, I usually use the int method like below.
Of course, application.roundup is also correct.

Sub test()
Dim a, b
a = 112
b = 10
'MsgBox Application.RoundUp(a / b, 0)
MsgBox -Int(-a / b)
End Sub

Ryanchris
10-21-2019, 08:40 AM
Worked perfectly. Thank you all so much! Huge help for this newby...

Ryanchris
10-21-2019, 11:55 AM
Quick correction...it works perfectly unless no data is entered. See the code below. HQX = Text box where the answer is recorded. HFX = first data point, 100 for example. HCL is always the same number between 2 and 20 - whatever the user selects.
If the user skips the HF1 box and enters data in the HF2 box, the code breaks. If there is a number in every HFX box, the code works perfectly.
Private Sub Hcalculate_Click()
'MsgBox Application.RoundUp(a / b, 0)
HQ1 = -Int(-HF1 / HCL)
HQ2 = -Int(-HF2 / HCL)
HQ3 = -Int(-HF3 / HCL)
HQ4 = -Int(-HF4 / HCL)
HQ5 = -Int(-HF5 / HCL)
HQ6 = -Int(-HF6 / HCL)
HQ7 = -Int(-HF7 / HCL)
HQ8 = -Int(-HF8 / HCL)
HQ9 = -Int(-HF9 / HCL)

Artik
10-21-2019, 12:16 PM
Private Sub Hcalculate_Click()
Dim i As Long

On Error Resume Next
For i = 1 To 9
With Me.Controls("HQ" & i)
.Value = vbNullString
.Value = -Int(-CDbl(Me.Controls("HF" & i).Value) / CDbl(HCL.Value))
End With
Next i
On Error GoTo 0

End Sub
First, each of the HQx controls will be cleared, and then a calculation attempt will be made. If any of the HFx or HCL fields are empty, an error will occur that was "handled" with the On Error Resume Next command, which instructs you to ignore runtime errors.

Artik

Ryanchris
10-21-2019, 12:44 PM
That is brilliant. Works perfectly! Thank you!