Sunday, November 15, 2009

Simple Input and Output with VBA

You already know how to get input from the user through the use of the Value property of a spreadsheet cell. Apart from that, you can also generate output for the user through the spreadsheet. However there may be times when you want something more dynamic and dramatic way to interact with the user than using a spreadsheet cell. The most common method for gathering input from the user and sending output back is the InputBox() and MsgBox() functions.


Inputbox

The inputbox function is used for prompt and take user response.It uses for take the user response before program execute.

Figure below shows the dialog box.


Now the how you can display a box like this which can get the user input
So following is the code

Sub inputboxexample()
dim myname as string
myname = inputbox("Enter Your Name")
End Sub

Syntax for Inputbox is following
InputBox(prompt[, title] [, default] [, xpos] [, ypos] [, helpfile, context])

Now let suppose we want to take a user input by the help of input box and want to print it on active workbook sheet1 in A1 cell

So the code is following.

sub inputboxexample
dim myname as string
myname = inputbox("Enter Your Name","Experiment")
activeworkbook.sheet1.cells(1,1).value = myname
End Sub

Inputbox is help a programmer in many things it can be use for design a beautiful program. And show it drammatically.


Msgbox()

So friend when a user think about a good program. He only think about its dramatically look. Means how the program took input from user. and how it shows the result output.

So for output we can use the msgbox().



For the following output we must be write a code and the code is following

Sub msgboxexample()
Dim myname As String
myname = InputBox("Enter Your Name")
MsgBox "So Your Name is " & myname
End Sub

and when the program prompt for Enter Your Name, write RED DEVIL on the box and press enter.

The syntax of the msgbox()function is following
Msgbox(Prompt, [Button As vbMsgBoxStyle = vbOkOnly],[Title],[Help File],[Context]) As vbmsgboxresult


So friend now you can use inputbox and msgbox function for give your program a drammatically look.

Remember one thing "imagination is more important than knowldge"

No comments:

Subscribe Now: From your browser

Search:

Learn Office Excel