Error while comparing msgbox with textbox in vba - vba

I am new to VBA. I have created a program in VBA that compares a msgbox value with a textbox value, but the result is not right. I have copied the code below. What have I done wrong on this? Please help me.
Private Sub CommandButton1_Click()
Dim num As String
num = Application.InputBox("enter num")
If TextBox1.Value * num > TextBox2.Value Then
MsgBox "textbox1 is higher"
Else
MsgBox "textbox2 is higher"
End If
End Sub

You need an input validation before processing it
like follows
Option Explicit
Private Sub CommandButton1_Click()
Dim num As Long, tb1Val As Long, tb2Val As Long
Const DEFNUM As Long = 1 '<--| define a default value for 'num'
If Not ValidateInput(tb1Val, tb2Val) Then Exit Sub '<--| exit if textboxes have improper input
num = Application.InputBox("enter num", , DEFNUM, Type:=1) '<-_| 'Type:=1' forces a number input
With Me
If tb1Val * num > tb2Val.Value Then
MsgBox "textbox1 is higher"
Else
MsgBox "textbox2 is higher"
End If
End With
End Sub
Function ValidateInput(tb1Val As Long, tb2Val As Long) As Boolean
With Me
If IsNumber(.TextBox1) And IsNumber(.TextBox2) Then
tb1Val = CLng(.TextBox1.Value)
tb2Val = CLng(.TextBox2.Value)
ValidateInput = True
Else
MsgBox "Improper textbox input, try again", vbCritical
End If
End With
End Function
as you can see:
demanded to Function ValidateInput() the validation of relevant userfom input
you may want to change it to suit your actual needs
used Application.InputBox() function instead of VBA.InputBox() to exploit its Type parameter and force the input to a number
I assumed you need Long numbers, should not this be the case just change all Long occurrences with the needed data type (Double, Integer,...) and CLng() with corresponding Type conversion function (CDbl(), CInt(), ...

You Need to make sure all values you are getting from the InpoutBox and TextBox are numbers (in my code converted to Long , just to be on the safe side):
Private Sub CommandButton1_Click()
Dim num As Long
' convert the number received from the InputBox to a number (type Long)
num = CLng(Application.InputBox("enter num"))
If CLng(TextBox1.Value) * num > CLng(TextBox2.Value) Then
MsgBox "textbox1 is higher"
Else
MsgBox "textbox2 is higher"
End If
End Sub

What you had to do was just use the Val() function when getting the TextBox values. which means you had to use Val(TextBox1.Value) instead of TextBox1.Value
Private Sub CommandButton1_Click()
Dim num As String
num = Application.InputBox("enter num")
If Val(TextBox1.Value) * num > Val(TextBox2.Value) Then
MsgBox "textbox1 is higher"
Else
MsgBox "textbox2 is higher"
End If
End Sub

Related

MS Access - Updating a cell's value

My customer wants to be able to autosum values within a cell. For example, they type in a new value, and this value will be added to the previous one, all within one cell (they don't want another field).
So far, I have 2 forms that will calculate the new value with one they input into the calculator, but it only functions for one cell.
Option Compare Database
Function MyVal(lnIn As Long)
If Len(Me.entry) > 1 Then
Me.entry = Replace(Me.entry, ".", "") & lnIn
'Me.entry = Left(Me.entry, Len(Me.entry)) & "." & Right(Me.entry)
Else
Me.entry = Me.entry & lnIn
End If
End Function
Private Sub calc_Click()
Me.Balance = Me.Balance - (-(Me.entry))
Me.entry = ""
End Sub
Private Sub clear_Click()
Me.entry = ""
End Sub
Private Sub Command16_Click()
Dim MyBalance As Currency
MyBalance = Me.Balance
DoCmd.Close
Forms!frmHours.Form.SetFocus
Forms!frmHours.Form.Balance = MyBalance
End Sub
Private Sub Form_Open(Cancel As Integer)
Me.Balance = OpenArgs
End Sub
Is there a way to move the "selected" cell value into the table I have (replacing the old value), do the calculations, and then move the new value back into the selected cell?

Passing Values in VBA

In the code I am posting, I am using a check box called "ACDS Test" and whenever it is checked it creates a sheet, then when it becomes unchecked it calls the upper function and deletes the sheet.
I am trying to add a message box that essentially works like a fail safe to ensure they want to delete the page. If they say they do not want to delete the page then I want the checkbox to stay checked.
For some reason I am getting this error message when I try to pass the value to make sure the checkbox stays checked and I cannot figure out why.
The error comes up on the line:
Sub ACDSTest_Click(CorrectValue As Integer)
And the specific error is: "Compile error: Procedure Declaration does not match description of event or procedure having the same name".
Any help is much appreciated! IF any more clarification is needed please feel free to ask!
Sub DeleteWorksheet(NameSheet As String)
Dim Ans As Long
Dim t As String
Dim CorrectValue As Integer
Dim i As Long, k As Long
k = Sheets.Count
Ans = MsgBox("Would you like to take this test off of the form?", vbYesNo)
Select Case Ans
Case vbYes
'Code reads through each page and finds one with corresponding name to string t
'Once it finds the correct page, it deletes it
For i = k To 1 Step -1
t = Sheets(i).Name
If t = NameSheet Then
Sheets(i).Delete
End If
Next i
CorrectValue = 0
Case vbNo
CorrectValue = 1
End Select
End Sub
Sub ACDSTest_Click(CorrectValue As Integer)
Dim NameSheet As String
Dim NameValue As String
NameSheet = "ACDS"
NameValue = "ACDS Test"
If ACDSTest.Value = True Then
CreateWorksheet (NameSheet), (NameValue)
Worksheets("Sheet1").Activate
Else
DeleteWorksheet (NameSheet)
If CorrectValue = 1 Then
ActiveSheet.Shapes("ACDS Test").ControlFormat.Value = 1
End If
End If
End Sub
The issue here is that the CorrectValue variable as you define it in DeleteWorksheet does not exist in the context of the
variable does not exist in context of the ACDSTest_Click subroutine. This is because variables defined within subroutines or functions are local to those functions. To correct this I would convert DeleteWorksheet to a function such as the below.
Further, the event that fires Private Sub ACDSTest_Click() cannot handle passing a value to that function, so changing it to Sub ACDSTest_Click(CorrectValue As Integer) causes an error.
Function DeleteWorksheet(ByVal SheetName As String) As Boolean
On Error GoTo SheetDNE
SheetName = Sheets(SheetName).Name 'Check if sheet exists w/o other objects
On Error GoTo 0
Select Case MsgBox("Would you like to take this test off of the form?", vbYesNo)
Case vbYes
Application.DisplayAlerts = False
Sheets(SheetName).Delete
Application.DisplayAlerts = True
DeleteWorksheet = True
Case Else: DeleteWorksheet = False
End Select
Exit Function 'Exit The Function w/o error
SheetDNE: 'Sheet Does Not Exist
MsgBox "The indicated sheet, " & SheetName & ", does not exist", vbOKOnly
End Function
And
Private Sub ACDSTest_Click()
Dim NameSheet As String
Dim NameValue As String
NameSheet = "ACDS"
NameValue = "ACDS Test"
If ACDSTest.Value = True Then
CreateWorksheet (NameSheet), (NameValue)
Worksheets("Sheet1").Activate
Else
If Not DeleteWorksheet(NameSheet) Then _
ActiveSheet.Shapes("ACDS Test").ControlFormat.Value = 1
End If
End Sub

Pricing a European Option using Simulaitons

I have created a user form that allows the user to change the various variables involved in pricing an option (Exercise Price, volatility..etc) along with allowing the user to change the simulations needed to arrive at the Price (or mean price in this case). However, I am unable to call the public subs within my code once I click the OK Button. Any suggestions on what I'm doing wrong would be greatly appreciated. [I have also included a picture of my user form below]
Option Explicit
Private cancel As Boolean
Public Function ShowInputsDialog(currentPrice As Single, _
exercisePrice As Single, riskfreeRate As Double, _
volatility As Single, duration As Single, simulation As Double) As Boolean
Call Initialize
Me.Show
If Not cancel Then
'Capture the other inputs.
currentPrice = txtCurrentPrice.Text
exercisePrice = txtExercisePrice.Text
riskfreeRate = txtRiskfreeRate.Text
volatility = txtVolatility.Text
duaration = txtDuration.Text
simulation = txtSimulation.Text
ShowInputsDialog = Not cancel
Unload Me
End Function
Public Sub ErrorCheck()
' Perform error checking for user inputs.
If IsNumeric(currentPrice) = False Or currentPrice < 0 Then
MsgBox ("Please enter a numeric value for the Current Price")
End If
If IsNumeric(exercisePrice) = False Or exercusePrice < 0 Then
MsgBox ("Please enter a positive numeric value for the exercise price")
End If
If IsNumeric(riskfreeRate) = False Then
MsgBox ("Please enter a numerical value for the risk-free rate")
End If
If IsNumeric(volatility) = False Then
MsgBox ("Please enter a numerical value for the Standard deviation")
End If
If IsNumeric(duration) = False Then
MsgBox ("Please enter a numerical valye for duration")
End If
End Sub
Public Sub Call_Eur(currentPrice As Single, _
exercisePrice As Single, riskfreeRate As Double, _
volatility As Single, duration As Single, simulation As Double)
Dim stockPrice As Single
Dim CallcashflowTermination As Single
Dim PutcashflowTermination As Single
Dim CalldiscountedValue As Double
Dim PutdiscountedValue As Double
Dim i As Integer
Dim CallMean As Double
Dim PutMean As Double
Dim arrayCallPrice() As Integer
Dim arrayPutPrice() As Integer
For i = 1 To simulation
' stock price
stockPrice = currentPrice * Exp((riskfreeRate - 0.5 * volatility ^ 2) * duration + volatility * Application.WorksheetFunction.Norm_Inv(Rnd(), 0, 1) * Sqr(duration))
' option cash flow at termination
CallcashflowTermination = Application.WorksheetFunction.Max(0, stockPrice - exercisePrice)
PutcashflowTerminatio = Application.WorksheetFunction.Funciton.Max(0, exercisePrice - stockPrice)
' discounted value of the option
CalldiscountedValue = CallcashflowTermination * Exp(-duration * riskfreeRate)
PutdiscountedValue = PutcashflowTermination * Exp(-duration * riskfreeRate)
arrayCallPrice(i) = CalldiscountedValue
arrayPutPrice(i) = PutdiscountedValue
CallMean = Application.WorsheetFunction.Average(arrayCallPrice)
PutMean = Application.WorksheetFunction.Average(arrayPutPrice)
Next i
MsgBox "The Call option price is " & CallMean & " the Put option price is " & PutMean
End Sub
Private Sub CmdCancel_Click()
Me.Hide
cancel = True
End Sub
Private Sub CmdOK_Click() '<--- ERROR!!!
Call Call_Eur(currentPrice As Single, _
exercisePrice As Single, riskfreeRate As Double, _
volatility As Single, duration As Single, simulation As Double)
End Sub
Private Sub UserForm_Click()
End Sub
BIG RED FLAG!!!!
When calling a subroutine. you need to pass values into it. Not redefine it's parameters.
Private Sub CmdOK_Click() '<--- ERROR!!!
Call Call_Eur(12.50, 13.43, 14, 33.56, 100, 13.67)
End Sub
I prefer removing the parenthesis and not using Call at all.
Private Sub CmdOK_Click() '<--- ERROR!!!
Call_Eur 12.50, 13.43, 14, 33.56, 100, 13.67
End Sub

How do I validate a group of textboxes by only numbers, no <> 12 and not empty in vba

Private Sub txt_dd_sku12_beforeUpdate(Cancel As Integer)
''start data validation by (len), (numeric) ''
If Len(Trim(txt_dd_sku12)) <> 12 Then
txt_dd_sku12.BackColor = RGB(116, 174, 244)
MsgBox ("the entry must be a 12 Digit SKU only")
Cancel = True
Exit Sub
End If
If Not IsNumeric(Trim(txt_dd_sku12)) Then
MsgBox " Highlighted field can not be blank. entry DD'S Sku12 to proceed further"
txt_dd_sku12.BackColor = RGB(116, 174, 244)
Cancel = True
Exit Sub
End If
End Sub
i have a 5 textboxes the i have to validate by, before update insert in my table when i press enter in my last textbox, but if i go back to an early textbox dont insert data until i press enter.
only numbers
not empty
no more or less of 12 digits
What your are looking for is the forms before update event. That will keep you from moving to a new record until your individual field requirements have been met.
Public Function ValidField(ctl as Control, FieldLength as integer) as Boolea
If Not IsNumeric(ctl) then
MsgBox "Highlighted field can not be blank. Enter an appropriate text."
ctl.backColor = RGB(116, 174, 244)
DoCmd.CancelEvent
Exit Function
End if
if len(ctl) <> FieldLength or IsNull(ctl) or ctl = "" then
MsgBox "The entry must be a 12 digit sku only."
ctl.BackColor = RGB(116,174,244)
DoCmd.CancelEvent
Exit Function
End if
ValidField = true
End Function
Private Sub Form_BeforeUpdate(Cancel As Integer)
If Not ValidField(txtBox1, 7) Then
Exit Sub
End If
End Sub
Change
If Len(Trim(txt_dd_sku12)) <> 12
To
If Len(Trim(txt_dd_sku12)) <> 12 And IsNumeric(Trim(txt_ss_sku12)) And Trim(txt_ss_sku12) <> vbNullString

Creating comboboxes in loop VBA

Hey guys I want to create a certain amount of combo boxes when a commandbutton is pressed. I cant figure out how to do it so I will really appreciate your help. This is the code ive created:
Private Sub CommandButton1_Click()
Dim AttPoints As Integer, Result As String
Range("E1:Z4").ClearContents
AttPoints = Range("B2").Value
If AttPoints = 0 Then
Result = "You have selected 0 AttPoints!"
ElseIf AttPoints < 0 Then
Result = "You have selected a negative amount of AttPoints!"
ElseIf AttPoints > 0 Then
Dim i As Integer
For i = 5 To (AttPoints + 4)
Cells(1, i).Value = "Attachment point:" & (i - 4)
Next i
End If
Range("A1") = Result
End Sub
In the for loop I create a row of cells in which the text attachment point is placed.
Under these texts i want the same amount of comboboxes as can be seen in the picture.
Add the following bit of code inside your loop
Private Sub CommandButton1_Click()
...
Shapes.AddOLEObject ClassType:="Forms.Combobox.1", _
Left:=Cells(2, i).Left, Top:=Cells(2, i).Top, _
Width:=Cells(2, i).Width, Height:=Cells(2, i).Height * 2
...
End Sub
That should produce your desired result.