VBA example - Excel 2007: VBA if else example

VBA if else example

VBA for Excel 2007: -VBA code example on using conditional statement if-else

In this example, We use VBA If-Else statement to detect number keys input in to the text box(TextBox1). If the user types a character that is not a number(from 0 to 9), it is not allowed to exist in the textbox. Only the number key is allowed.

   To run this example VBA code, you will need a Form and one TextBox.

VBA for Excel: VBA code example of using If Else statment to detect number key pressed.

VBA code to detect keys pressed:

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

  If KeyAscii >= 48 And KeyAscii <= 57 Then
     Exit Sub
  Else: KeyAscii = 0
  End If

End Sub


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.