I Need a help in Excel VBA. I want to develop a function that will automatically apply the function to selected range of Cells. My Sample Code is Here it work Independently for a single row I want to apply it for minimum 500 rows.
Sub Value() ' ' Value For the Insurance Rate
Dim percentage As Double
Dim year As Double
percentage = Sheet5.Range("R2").Value
year = Sheet5.Range("Q2").Value
If percentage <= 85 And year <= 25 Then
Sheet5.Range("S2").Value = Sheet4.Range("D13").Value
ElseIf percentage <= 85 And year > 25 Then
Sheet5.Range("S2").Value = Sheet4.Range("C13").Value
ElseIf percentage > 85 And percentage <= 90 And year <= 25 Then
Sheet5.Range("S2").Value = Sheet4.Range("D8").Value
ElseIf percentage > 85 And percentage <= 90 And year > 25 Then
Sheet5.Range("S2").Value = Sheet4.Range("C8").Value
ElseIf percentage > 90 And percentage <= 95 And year <= 25 Then
Sheet5.Range("S2").Value = Sheet4.Range("D5").Value
ElseIf percentage > 90 And percentage <= 95 And year > 25 Then
Sheet5.Range("S2").Value = Sheet4.Range("C5").Value
ElseIf percentage > 95 And year <= 25 Then
Sheet5.Range("S2").Value = Sheet4.Range("D3").Value
ElseIf percentage > 95 And year > 25 Then
Sheet5.Range("S2").Value = Sheet4.Range("C3").Value
End If
End Sub
You're pretty close. I just converted your procedure into a User Defined Function, which can then be used like built-in Excel functions in the Excel Window.
Here's the code:
Function myValue(percentage As Double, year As Double) ''Value For the Insurance Rate
If percentage <= 85 And year <= 25 Then
myValue = Sheet4.Range("D13").Value
ElseIf percentage <= 85 And year > 25 Then
myValue = Sheet4.Range("C13").Value
ElseIf percentage > 85 And percentage <= 90 And year <= 25 Then
myValue = Sheet4.Range("D8").Value
ElseIf percentage > 85 And percentage <= 90 And year > 25 Then
myValue = Sheet4.Range("C8").Value
ElseIf percentage > 90 And percentage <= 95 And year <= 25 Then
myValue = Sheet4.Range("D5").Value
ElseIf percentage > 90 And percentage <= 95 And year > 25 Then
myValue = Sheet4.Range("C5").Value
ElseIf percentage > 95 And year <= 25 Then
myValue = Sheet4.Range("D3").Value
ElseIf percentage > 95 And year > 25 Then
myValue = Sheet4.Range("C3").Value
End If
End Function
Then in cell S2 (or any other cell you want to use the function) you would enter
=myValue(R2,Q2)
Also note, that I change the name of the function to myValue to not run into issues with the built in Value members in VBA.
Related
I'm designing a software that does basic payroll for a school project. I'm stuck on this one part where I have to figure out what the federal tax will be based on the employee salary. This is the chart that tells you the rate of the tax based on salary range.
I tried this code,
Dim federaltaxrate As Integer
Dim federaltax = (salary.Text * federaltaxrate)
If salary.Text >= 0 Then
If salary.Text <= 50 Then
federaltaxrate = 0
End If
ElseIf salary.text <= 500 Then
If salary.Text >= 50 Then
federaltaxrate = 0.1
End If
ElseIf salary.text <= 2500 Then
If salary.Text >= 500 Then
federaltaxrate = 45 + 0.15 * salary.Text - 500
End If
ElseIf salary.text <= 5000 Then
If salary.Text >= 2500 Then
federaltaxrate = 345 + 0.2 * salary.Text - 2500
End If
ElseIf salary.text >= 5000 Then
federaltaxrate = 845 + 0.25 * salary.Text - 5000
End If
Else
End If
I have a listbox that shows other information as well but this is what I used to show the calculated info in the listbox.
ListBox1.Items.Add("Federal Tax: $" + federaltax.ToString)
When I run this code and input in a random salary, the federal tax shows up as 0.
Do I need to convert the salary into weekly gross pay, if so how would I go on about writing the code that finds the federal tax rate based on the salary and it's range.
You might be having trouble with order of precedence of the arithmetic operations. I think a Select Case is cleaner.
Private Function GetFederalTax(GrossPay As Decimal) As Decimal
Dim FederalTax As Decimal
Select Case GrossPay
Case < 50
FederalTax = 0
Case < 500
FederalTax = CDec((GrossPay - 51) * 0.1)
Case < 2500
FederalTax = CDec(((GrossPay - 500) * 0.15) + 45)
Case < 5000
FederalTax = CDec(((GrossPay - 2500) * 0.2) + 345)
Case Else
FederalTax = CDec(((GrossPay - 5000) * 0.25) + 845)
End Select
Return FederalTax
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim grossPay As Decimal
If Decimal.TryParse(TextBox1.Text, grossPay) Then
Dim tax = GetFederalTax(grossPay)
Debug.Print($"Gross {grossPay} Tax {tax}")
ListBox1.Items.Add(String.Format("Federal Tax {0}, Gross Pay {1}", tax, grossPay)) '***EDIT***
Else
MessageBox.Show("Please enter a valid number.")
End If
End Sub
The sample test produced the following in the Immediate Window.
Gross 45 Tax 0
Gross 700 Tax 75
Gross 8000 Tax 1595
Gross 2501 Tax 345.2
Gross 2800 Tax 405
Firstly, your Boolean logic is all wrong. If the salary value was 51, you'd satisfy the first outer condition (>= 0) and then fail the first inner condition (<= 50). There would not be any further comparisons performed - which you would know if you'd debugged - so no tax calculation would ever be performed.
Secondly, your calculations are OK but you're misusing the results. Those calculation get the amount of tax to be paid, not the rate. The rates are 10%, 15%, 20% and 25%, which are already contained in your calculations. Get rid of that second variable and just assign the results of appropriate calculations to the one variable.
I would do it like this:
Dim salaryAmount = CDec(salary.Text)
Dim taxAmount As Decimal = Decimal.Zero
If salaryAmount > 5000D Then
taxAmount = 845D + 0.25D * (salaryAmount - 5000D)
ElseIf salaryAmount > 2500D Then
taxAmount = 345D + 0.2D * (salaryAmount - 2500D)
ElseIf salaryAmount > 500D Then
taxAmount = 45D + 0.15D * (salaryAmount - 500D)
ElseIf salaryAmount > 50D Then
taxAmount = 0.1D * (salaryAmount - 50D)
End If
'Use taxAmount here.
This uses appropriate data types throughout, i.e. it does not perform arithmetic on String values and it uses Decimal for currency values. The D suffix on the literals forces them to be type Decimal rather than Integer or Double.
It also works from biggest to smallest to simplify the Boolean expressions.
The Nested If should be combined like below as it is missing few cases
If salary.Text >= 0 And salary.Text <= 50 Then
federaltaxrate = 0
ElseIf salary.text <= 500 And salary.Text >= 50 Then
federaltaxrate = 0.1
ElseIf salary.text <= 2500 AND salary.Text >= 500 Then
federaltaxrate = 45 + 0.15 * salary.Text - 500
End If
So I was just wondering how to calculate an average in visual basic code?
I currently have a form created and the user is to enter 6 numbered for 6 courses and they must be in textboxes. I know that average is the 6 numbers added together divided by the count but I don't know how to grab the numbers from the textbox to calculate the average.
I've searched online for the answer to this but nothing pertains to this exact problem. My textbook is also of no help.
Any help would be greatly appreciated.
Dim input As Integer
If Integer.TryParse(InputTextbox1.Text, input) Then
If input >= 92 And input <= 100 Then
OutputTextbox1.Text = "A+"
ElseIf input >= 88 And input <= 91 Then
OutputTextbox1.Text = "A"
ElseIf input >= 85 And input <= 87 Then
OutputTextbox1.Text = "A-"
ElseIf input >= 82 And input <= 84 Then
OutputTextbox1.Text = "B+"
ElseIf input >= 78 And input <= 81 Then
OutputTextbox1.Text = "B"
ElseIf input >= 75 And input <= 77 Then
OutputTextbox1.Text = "B-"
ElseIf input >= 72 And input <= 74 Then
OutputTextbox1.Text = "C+"
ElseIf input >= 68 And input <= 71 Then
OutputTextbox1.Text = "C"
ElseIf input >= 65 And input <= 67 Then
OutputTextbox1.Text = "C-"
ElseIf input >= 55 And input <= 64 Then
OutputTextbox1.Text = "D"
ElseIf input <= 54 Then
OutputTextbox1.Text = "F"
End If
Else
ErrorTextbox.Text = "Please ensure that what you input is a number between 0 and 100"
End If
This is the code I have currently there is 6 textboxes using the above code to transfer numbers to letters. The numbers that the user enters is what i need to calculate into the average.
Thanks
Try this:
first thing i did is that i total all textbox numbers and then divide to total number so that i can get the average
Note: dont allow textbox to input a letters because it will error
i converted the textbox text to double so that it will consider as number and not letters.
Public Class Form4
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim average As Double = 0.0
Dim total As Double = 0.0
total = CDbl(TextBox1.Text) + CDbl(TextBox2.Text) + CDbl(TextBox3.Text) + CDbl(TextBox4.Text) + CDbl(TextBox5.Text) + CDbl(TextBox6.Text)
average = total / 6
TextBox7.Text = average.ToString()
End Sub
End Class
Modified: The label_grade is the letter of the grade
Public Class Form4
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim average As Double = 0.0
Dim total As Double = 0.0
total = CDbl(TextBox1.Text) + CDbl(TextBox2.Text) + CDbl(TextBox3.Text) + CDbl(TextBox4.Text) + CDbl(TextBox5.Text) + CDbl(TextBox6.Text)
average = total / 6
TextBox7.Text = average.ToString()
If average >= 92 And average <= 100 Then
label_Grade.Text = "A+"
ElseIf average >= 88 And average <= 91 Then
label_Grade.Text = "A"
ElseIf average >= 85 And average <= 87 Then
label_Grade.Text = "A-"
ElseIf average >= 82 And average <= 84 Then
label_Grade.Text = "B+"
ElseIf average >= 78 And average <= 81 Then
label_Grade.Text = "B"
ElseIf average >= 75 And average <= 77 Then
label_Grade.Text = "B-"
ElseIf average >= 72 And average <= 74 Then
label_Grade.Text = "C+"
ElseIf average >= 68 And average <= 71 Then
label_Grade.Text = "C"
ElseIf average >= 65 And average <= 67 Then
label_Grade.Text = "C-"
ElseIf average >= 55 And average <= 64 Then
label_Grade.Text = "D"
ElseIf average <= 54 Then
label_Grade.Text = "F"
End If
End Sub
I want to create a function which give me what contribution an employee has to make to a pension plan in function of its salary (with given down and upper limit) and in function of its age (doesn't contribute before 25 and after 64).
With the following code, I try to achieve that. I may have spend too much time on front of my screen but i don't see the problem. The debugger runs fine but I keep getting a "#Value!" alert. It may be the If-statment within another If. If someone may see where the problem could be, it would be very helpful
Option Explicit
Constant M = 1175
Function coti_min_LPP(x As Integer, salaire_AVS As Double)
Dim salaire_coord As Double
'The basis for the calculation uses the salary in different layers
If salaire_AVS < 18 * M Then
salaire_coord = 0
ElseIf salaire_AVS > 18 * M And salaire_AVS < 24 * M Then
salaire_coord = 3 * M
ElseIf salaire_AVS > 24 * M Then
salaire_coord = salaire_AVS - 21 * M
End If
'Under a certain limit, the contribution is a percentage of the basis
'according to the age
If salaire_AVS < 72 * M Then
If x < 25 Then
coti_min_LPP = 0
ElseIf x > 24 And x < 35 Then
coti_min_LPP = salaire_coord * 0.07
ElseIf x > 34 And x < 45 Then
coti_min_LPP = salaire_coord * 0.1
ElseIf x > 44 And x < 55 Then
coti_min_LPP = salaire_coord * 0.15
ElseIf x > 54 And x < 65 Then
coti_min_LPP = salaire_coord * 0.18
ElseIf x > 64 Then
coti_min_LPP = 0
End If
Else
'Above the limit, it is the percentage of a fixed amount
If x < 25 Then
coti_min_LPP = 0
ElseIf x > 24 And x < 35 Then
coti_min_LPP = 51 * M * 0.07
ElseIf x > 34 And x < 45 Then
coti_min_LPP = 51 * M * 0.1
ElseIf x > 44 And x < 55 Then
coti_min_LPP = 51 * M * 0.15
ElseIf x > 54 And x < 65 Then
coti_min_LPP = 51 * M * 0.19
ElseIf x > 64 Then
coti_min_LPP = 0
End If
End If
End Function
There are two immediate things that result in an issue:
Instead of Constant M = 1175 you should use Private Const M As Long = 1175. Why Long? Please look at the line If salaire_AVS < 72 * M Then if you add watch and go through your code in the debbuger you will find out that, if M is declared as an integer, after this line (according to watch window) M has value "out of context". This is basically due to the fact that you have achieved integer overflow. Please consider following code:
Example 1:
Sub test2()
Dim a As Integer
Dim b As Double
a = 1175
b = 15
Debug.Print b < 72 * a
End Sub
Option Explicit is a good practice, however requires you to declare all of the variables in your code. Declare them. You may remove Option Explicit for testing purposes. Some lecture on variable declaration: http://www.excelfunctions.net/VBA-Variables-And-Constants.html
After above changes your function works for me (tested =coti_min_LPP(27,19*1175))
Hope that helps. Btw. Please notice that having so many nested ifs with hardcoded values is troublesome to maintain, control and usually is not considered as good coding practice.
I'm building a little program to help out with some data imports and for our techs when out on sites.
The bit I'm struggling with is the bp check, see code below:
Private Sub bphg_afterupdate()
'blood pressure values
'below 100/60 - low
'120/70 - normal
'140/90 - high, gp review
'180/100 - high, cut off for fitness for driving
'200/100 - high, cut off for driving/spiro
'230/120 - urgent review required
If bpmm <= 100 Or bphg <= 60 Then
bpcomment.Value = "LOW! - Seek Advice"
ElseIf bpmm < 140 Or bphg < 90 Then
bpcomment.Value = "Normal BP"
ElseIf bpmm < 180 Or bphg < 100 Then
bpcomment.Value = "High! - GP Review"
ElseIf bpmm < 200 Then
bpcomment.Value = "High! - Temp restriction to driving MPE/FLT"
ElseIf bpmm < 230 Or bphg < 120 Then
bpcomment.Value = "High! - To high for Spiro & Temp Driving Resitricion MPE/FLT"
Else
bpcomment.Value = "URGENT! - Review required"
End If
End Sub
What it's doing is finding the first value that fits in either the values specified and then stopping. It should be continuing to check other criteria.
So basically with blood pressure, out of the 2 figures your doctor gives you, either can determine if your bp is ok or not. So when we enter a bp into the form say 200/80 (you would probably never get this but I'm being through), it would find that the first figure is high and the second is normal. My script however is finding the second figure being normal first without checking the first figure, so it just displays "normal" when in fact it's "high".
Select Case would be a better way to deal with the blood pressure issues:
Option Explicit
Public Sub TestMe()
Dim bpmm As Long
Dim bphg As Long
bpmm = 100 'assign these two somehow. E.g.-> bpmm = ActiveSheet.Range("A1")
bphg = 100
Select Case True
Case bpmm <= 100 Or bphg <= 60
Debug.Print "LOW! - Seek Advice"
Case bpmm < 140 Or bphg < 90
Debug.Print "Normal BP"
Case bpmm < 180 Or bphg < 100
Debug.Print "High!"
Case Else
Debug.Print "URGENT! - Review required"
End Select
End Sub
Instead of Debug.Print, you may put your business logic there. Just make sure that you order the conditions correctly - if the first condition is evaluated to TRUE, the check does not go further.
There is a tiny performance advantage of Select Case - Which way is faster? If elseif or select case
Edit: If your logic is, that all the criteria should be checked separately and independently, then take a look at this:
Public Sub TestMe()
Dim bpmm As Long
Dim bphg As Long
bpmm = 100 'assign these two somehow. E.g.-> bpmm = ActiveSheet.Range("A1")
bphg = 100
If bpmm <= 100 Or bphg <= 60 Then
Debug.Print "LOW! - Seek Advice"
End If
If bpmm < 140 Or bphg < 90 Then
Debug.Print "Normal BP"
End If
If bpmm < 180 Or bphg < 100 Then
Debug.Print "High!"
End If
End Sub
From your description, it looks like you want to return the result of the highest one of the two criteria. In this case, you will need to reverse the order of the checks:
If bpmm >= 230 Or bphg >= 120 Then
bpcomment.Value = "URGENT! - Review required"
ElseIf bpmm >= 200 Then
bpcomment.Value = "High! - To high for Spiro & Temp Driving Resitricion MPE/FLT"
ElseIf bpmm >= 180 Or bphg >= 100 Then
bpcomment.Value = "High! - Temp restriction to driving MPE/FLT"
ElseIf bpmm >= 140 Or bphg >= 90 Then
bpcomment.Value = "High! - GP Review"
ElseIf bpmm >= 120 Or bphg >= 70 Then
bpcomment.Value = "Normal BP"
Else
bpcomment.Value = "LOW! - Seek Advice"
End If
However, it's not clear from the instructions (that you have at the top of your function) what to do in the case it is between 100/60 and 120/70. The code above considers it LOW. If you want to consider it NORMAL instead, then change the last ElseIf from:
ElseIf bpmm >= 120 Or bphg >= 70 Then
to:
ElseIf bpmm >= 100 Or bphg >= 60 Then
I'm building a little time > pay conversion program in VB. I'm really new to VB and don't understand why my variable pay doesn't calculate like it should. I plug in 5 5's as a test and get $0.
Dim total As Double = 0.0
Dim timeCounter As Integer = 0
Dim time As Integer = 0
Dim pay As Double = 0.0
While timeList.Items.Count < 5
time = timeList.Items(timeCounter)
total += time
timeCounter += 1
End While
If total >= 0 And total <= 40 Then
If total >= 0 And total <= 20 Then
pay = total * 10
ElseIf total >= 21 And total <= 30 Then
pay = total * 12
ElseIf total >= 31 And total <= 40 Then
pay = total * 15
Else
PayLabel.Text = "Error"
End If
End If
PayLabel.Text = "$" & pay
Your syntax should be something like this:
For intCount = 0 To timeList.Items.Count
time = timeList.Items(intCount)
total += time
Next intCount
This will avoid an infinite loop.
To fix your 40+ issue:
If total >= 0 And total <= 40 Then
If total >= 0 And total <= 20 Then
pay = total * 10
ElseIf total >= 21 And total <= 30 Then
pay = total * 12
ElseIf total >= 31 And total <= 40 Then
pay = total * 15
End If
Else
PayLabel.Text = "Error"
End If
this would be my fix into a console apps
for process will return $0, second $100
Module Module1
Sub Main()
Dim timeList As New List(Of Integer)
timeList.AddRange(New Integer() {1, 2, 3, 4, 5, 6})
process(timeList)
timeList.Clear()
timeList.AddRange(New Integer() {1, 2, 3, 4})
process(timeList)
Console.Read()
End Sub
Private Sub process(timeList As List(Of Integer))
Dim total As Double = 0.0
Dim timeCounter As Integer = 0
Dim time As Integer = 0
Dim pay As Double = 0.0
While timeList.Count < 5 AndAlso timeCounter < timeList.Count
time = timeList(timeCounter)
total += time
timeCounter += 1
End While
If total >= 0 And total <= 40 Then
If total >= 0 And total <= 20 Then
pay = total * 10
ElseIf total >= 21 And total <= 30 Then
pay = total * 12
ElseIf total >= 31 And total <= 40 Then
pay = total * 15
Else
Console.WriteLine("error")
End If
End If
Console.WriteLine("$" & pay)
End Sub
End Module
This could be better solved with a functional approach. To get the sum of the list of integers do the following:
Dim totalTime = timeList.Sum()
Then you can follow the logic you laid out. I would highly recommend learning to use Linq Set Functions to make your code your readable and easier to understand. Good Luck.