How to do math in VBA in Word? - vba

As the 2020 tax season approaches, I'm trying to create a simple macro in Word that will take a few user inputs and populate an email template relating to stimulus checks to send to my clients. The actual macro just opens an info box with spaces for three user inputs. Inside of that box, there is an 'OK' button and a 'Cancel' button. The cancel button just hides the box, and the OK button performs the following:
Private Sub CommandButton1_Click()
Dim taxpayerName As Range
Set taxpayerName = ActiveDocument.Bookmarks("tpName").Range
taxpayerName.Text = Me.TextBox1.Value
Dim numberOfDep As Range
Set numberOfDep = ActiveDocument.Bookmarks("numDep").Range
numberOfDep.Text = Me.TextBox3.Value
Dim numberOfDep1 As Integer
numberOfDep1 = Me.TextBox3.Value
Dim maritalStatus As Range
Set maritalStatus = ActiveDocument.Bookmarks("mStatus").Range
maritalStatus.Text = Me.TextBox2.Value
Dim maritalStatus1 As Range
Set maritalStatus1 = ActiveDocument.Bookmarks("mStatus1").Range
maritalStatus1.Text = Me.TextBox2.Value
Dim maritalStatus2 As Range
Set maritalStatus2 = ActiveDocument.Bookmarks("mStatus2").Range
maritalStatus2.Text = Me.TextBox2.Value
Me.Repaint
tpInfo.Hide
Dim amount1 As Integer
If maritalStatus = "single" Then
amount1 = 1200
Else
amount1 = 2400
End If
amount1 = ActiveDocument.Bookmarks("a1").Range
End Sub
I'm trying to check my maritalStatus variable for 'single' and assign amount1 a value of either 1200 or 2400 for the first round of stimulus payments. I then want to insert that value into the Word document at bookmark a1 that I've created. However, I currently get the runtime error 13 on the last line of my code.
My end goal is to take amount1 and add it to a new variable (depAmount1) that would multiply $500 by the number of dependents, which should be stored in numberOfDep1. So a single taxpayer with 1 child would result in a total of $1,700. Then I would repeat the code with minor tweaks for the second round of stimulus payments and finally add the two totals together for the grand total.
Thanks in advance, any help would be greatly appreciated.

If the core of your question is the error on your last line of code, I think you're probably getting it because you're trying to assign a string from your bookmark to the amount1 variable, which is specified as an Integer, and I think you want to do the opposite, put the value into the document. Reversing your line of code should do the trick.
ActiveDocument.Bookmarks("a1").Range = amount1

Related

Excel VBA - Compile Error - Object Required

This is my first post to this wonderful forum . I am new to VBA and have been writing my first meaningful macro beside doing some practice while learning.
While the WIP code is reproduced below, let me give you a background.
Have a a sheet to calculation investment maturity based on various inputs like Term of Payment and term of Maturity.
This sheet has all the formule in place to compute the maturity value.
Now on sheet 2, I am creating a matrix structure with a intersection of payment term and term of maturity. For ex combination of 1 Yr of Payment term with maturity ( 1...25) and next Payment term and so on.
I am writing a macro which will pick up the user choice from sheet 1 and then loop the macro in matrix and capture the result and paste it to sheet two .
I am still far away from what i have to achive but got a code in first few line of selecting and setting the payment term and maturity terms
Error is Compile error- Object required. I am not able to figure out what it it. WIP code is reproduced below
Private Sub Simulation_Click()
Dim PPT As String
Dim Term As String
MsgBox (" The Programme is starting now")
Set PPT = Workbooks("himanshu.xlsm").Worksheet("Sheet1").Range("G2").Value
Set Term = Workbooks("himanshu.xlsm").Worksheet("Sheet1").Range("G3").Value
For PPT = 1 To PPT
For Term = 1 To Term
' Do something here
Next Term
Next PPT
End Sub
Please help
EDIT # 1- September 19,2017, 3.10 AM IST
Hi Experts,
Finally my first VBA code is running . Its slow but its running. One last problem
I have issue in Code line "Workbooks("himanshu.xlsm").Sheets("Sheet1").Range("J2").Copy Workbooks("himanshu.xlsm").Sheets("What if").Cells(cols, Rowsh)" where while to source carries the right value( checked in debug Mode) but when it is pasted to target, it is pasted as 0. When I checked the target sheet , somehow it is showing me a formula (= Max( R1C1 :X1Y1). Please note that from where I am copyiong the value ( Source) , its a excel calculation which is arrived as a formula of selecting max of col J . I suspect that code is copying the formula instead of value. Please advice
Option Explicit
Sub macro21()
'MsgBox ("Start")
Dim i As Integer, j As Integer
Dim PPT As Integer
Dim Term As Integer
Dim pptrange As Range ' Address of the Cell where PPT is maintained in Sheet 1
Dim termrange As Range ' Address of the Cell where Term is maintained in Sheet 1
Dim cols As Integer
Dim Rowsh As Integer
PPT = 3
Term = 5
cols = 3
Rowsh = 3
For i = 1 To PPT
For j = 1 To Term
Set pptrange = Workbooks("himanshu.xlsm").Sheets("Sheet1").Range("G2") ' Set pptrange and termrange locations
Set termrange = Workbooks("himanshu.xlsm").Sheets("Sheet1").Range("G3") ' Set pptrange and termrange locations
pptrange.Value = i
termrange.Value = j
***Workbooks("himanshu.xlsm").Sheets("Sheet1").Range("J2").Copy Workbooks("himanshu.xlsm").Sheets("What if").Cells(cols, Rowsh)***
' MsgBox ("Value is " & Cells(cols, Rowsh).Value)
MsgBox ("Value is " & Workbooks("himanshu.xlsm").Sheets("Sheet1").Range("J2"))
If j < Term Then
cols = cols
Rowsh = Rowsh + 1
End If
Next j
cols = cols + 1
Rowsh = 3
Next i
End Sub
I have issue in Code line "Workbooks("himanshu.xlsm").Sheets("Sheet1").Range("J2").Copy Workbooks("himanshu.xlsm").Sheets("What if").Cells(cols, Rowsh)" where while to source carries the right value( checked in debug Mode) but when it is pasted to target, it is pasted as 0. When I checked the target sheet , somehow it is showing me a formula (= Max( R1C1 :X1Y1). Please note that from where I am copyiong the value ( Source) , its a excel calculation which is arrived as a formula of selecting max of col J . I suspect that code is copying the formula instead of value. Please advice
PPT is a string so you should use:
PPT = ...
and not
Set PPT =
Set is used to assign object variables such as workbooks, worksheets, etc.
Edit: as Jeeped mentioned in his comment you have to change data type. You cannot use string in a loop like that. Change Term and PPT to Integer or Long.

Using a variable in coded date

I am trying to pull all data entries that are within a userform selected month and year. I can get the code to run fine when I hard code the year but I want the year to come off of a text box. I converted the Textbox value to an integer using Cint() and dim'd it to "Year" in my if statement. I can get it to work if I write Cdate("3/1/2016"), but I want see if there is a way to run it like: Cdate("3/1/Year"). I tried it this way and get a typematch error on the Cdate Im pretty new to VBA so excuse my stupidity.
Ignore the "Month" variable I was just using that to put a stop on the code and step it through to see if it would enter my if statement.
Thanks in advance.
My Code
Private Sub OKBtn_Click()
Dim Sales As Range
Dim Year As Integer
Dim Month As Integer
Dim i As Integer
Year = CInt(YearText.Value)
Set Sales = Worksheets("Sales").Range("A4")
i = 0
If Sales.Offset(i, 1).Value >= CDate("3/1/2016") And Sales.Offset(i, 1).Value <= CDate(" 3/31/2016 ") Then
Month = 1
End If
In order for the CDate to work, you need to seperate the stings inside the brackets to 2 parts
1.The constant, in your case "3/1/".
2.And the variable, CInt(YearText.Value).
Option Explicit
Private Sub OKBtn_Click()
Dim DDate As Date
DDate = CDate("3/1/" & CInt(YearText.Value))
' for debug only
MsgBox "Date entered is :" & DDate
End Sub

How do I grab the string and adjacent number in multiple columns

I want to run a loop to group the text by certain criteria and add up a total, but I need to be able to grab both bits of data.
Connecticut 624
Georgia 818
Washington 10
Arkansas 60
New Jersey 118
Ohio 2,797
The selection would be something like that, and I want the user to be able to highlight the two columns and I will run through and group the States by location and add the totals
edit--
So far, all I've been able to do is grab what the user selected range is:
Sub Short()
Dim rngMyRange As Range
If TypeName(Selection) = "Range" Then
Set rngMyRange = Selection
Else
Exit Sub 'Non-range type selection e.g. a chart
End If
MsgBox "The address of rngMyRange is " & rngMyRange.Address(False, False)
End Sub
I have a formula in another sheet that checks the states for their group, but it's one cell at a time
=IF( AND(D9="", B9="USA"),"",IF(B9="USA",IF(COUNTIF(Legends!$B$4:$B$13,D9)>0,"US Group 1",IF(COUNTIF(Legends!$F$4:$F$15,D9)>0,"US Group 3","US Group 2")),IF(COUNTIF(Legends!$H$4:$H$6,B9)>0,"Int'l Tier 1",IF(COUNTIF(Legends!$J$4:$J$15,B9)>0,"Int'l Tier 2","Int'l Tier 3"))))
Using the for loop below will loop through each cell in your range (selection - make sure you select just the column with the names in it)
Sub Short()
Dim rngMyRange As Range
Dim ttl as integer
Dim c
If TypeName(Selection) = "Range" Then
Set rngMyRange = Selection
Else
Exit Sub 'Non-range type selection e.g. a chart
End If
for each c in rngMyRange
ttl = ttl + c.offset(0,1)
next c
End Sub
You'll need to change the for loop with your criteria. This could be done a lot easier though by using a pivot table on your data range.

Excel VBA - Add or Reduce Amount in cell from cell reference

I'm trying to look for some VBA Code that can reduce the Quantity in stock whenever there is Item issued in Invoice. For Example if "Keyboard" and "Mouse" item issued by 2 and 3 then the number should automatically reduce in in Stock "Quantity" Column for respected item
I already search for the solution and couldn't get one. Hope you guys can help me.
Thank you in advance.
If you could add some more information about where the values are, and how your invoice event is called it would help.
Are you running this through a Form? or on a worksheet? If there are textBoxes with information, just use those when you declare your input variables below.
Anyway. This could easily be condensed, but I'm laying it out in a more informative way so you can learn the concepts behind it instead of the most concise code.
EDITED WITH REVISED CODE: After Comments with details. SEE PIC
Sub InventoryUpdate()
Dim qtyIn As Integer
Dim qtySold As Integer
Dim sheeteName As String
Dim iRow As Integer
Dim lastStockRow As Integer
Dim lastInvoiceRow As Integer
Dim tProduct As String
Dim sRow As Integer
'Declare the sheetName here once, so you don't have to replace it every time it changes
sheetName = "Sheet1"
'Determine the last rows, unless you know it already, then ignore this.
lastInvoiceRow = Sheets(sheetName).Range("B65536").End(xlUp).Row
lastStockRow = Sheets(sheetName).Range("E65536").End(xlUp).Row
'Loop through the rows of your table. Since you know the range, it's rows 4-10
For iRow = 4 To lastInvoiceRow
'Set the temp Product name as row, Column B, and the Qty Sold from Column C
tProduct = Sheets(sheetName).Cells(iRow, 2)
qtySold = Sheets(sheetName).Cells(iRow, 3)
For sRow = 4 To lastStockRow
If Sheets(sheetName).Cells(sRow, 5) = tProduct Then
qtyIn = Sheets(sheetName).Cells(sRow, 6)
Sheets(sheetName).Cells(sRow, 6) = qtyIn - qtySold
Exit For
End If
Next sRow
Next iRow
End Sub

Use an InputBox to enter prices of 4 items

I'm new to VB. Today I'm working on entering 4 prices for items to purchase using an input box. I need to create a counter in a loop. The only 2 buttons on the form "Enter Prices" and "Exit". So far this is the code I have (see below). I know something is off. When I run it, I'm allowed to enter 4 numbers. But at the end, when the message box comes up to show my total, it just gives me my last number I entered. I know I've got to change a few things, as I need my numbers to be in currency. Any suggestions as to where I need to go from here to get this up and running?
Private Sub btnPrices_Click(sender As Object, e As EventArgs) Handles btnPrices.Click
'Declare a variable as counter and accumulator
Dim intcount As Integer = 1I
Dim intAccumulator As Integer = 0I
'Declare and intialize variable
Dim strInput As String = ""
'Number of Items
Const intNUM_PRICES As Integer = 4
'Pre-test loop will keep iterating as long as the expression is ture.
Do While intcount <= intNUM_PRICES
'Get price of each item purchased
strInput = InputBox("Enter Price " & intcount, "Price Needed")
'Add 1 to the counter
intcount += 1
Loop
'Look at the value placed in the
MessageBox.Show("Your combined Price for all 4 items is: " & strInput)
End Sub
You've only got one variable for the input and each time you call InputBox you replace the previous value each time. If you want a total then you have to add the values, so you need to add the current input to the previous total each time, not replace it. Make sure that you convert the input to a number and use a numeric variable, because adding strings will actually join them, not add them mathematically.