I want to ask the user for a number, add that number to the value in the active cell, then place the result in a cell that is three rows up and two columns right of the active cell.
Sub AddNumbersB()
Dim x As Double
x = InputBox("Please enter a number")
ActiveCell.Offset(-3, 2).Value = x
You need to add that number
xto the value ofActiveCell. Right now you just write the valuexso change:If you would make this a solid procedure you would do something like the following:
Check if you can move 3 up and 2 right from the
ActiveCell. If that's not possible we need to choose another cell first.Make sure you use the Application.InputBox method where you can specify a
Type:=1so this box only accepts numbers. NoteApplication.InputBoxis different fromInputBox(which does not allow types).Also make sure to define the return value as
Variantbecause the Application.InputBox method will either return a number or returnFalseasBooleanin case of cancel.Then check if the user pressed the cancel button (so it doesn't perform the calculation and exits instead).
The Application.InputBox method will return a
Falseof typeBooleanon cancel. Why can't we just check forRetVal = Falseto identify the cancel? Because if the user enters0as a number this will be treated as cancel aswell becauseFalseand0is considered to be equal in VBA. Therfore we need to check if the type isBooleantoo!Finally if all conditions are met and the user entered a number and pressed OK we can perform the addition and write the result.