Numeric type check

Tags
Summary

Put a value into a string. Use the IsNumeric() function.

Situation

You want to check whether a value is a valid number.

Needs

A value to check.

Provides

A variable that you know is a number.

Action

Put the value you want to check into a string. For example, suppose we wanted to check whether user input for number of goats is a number:

  • Dim tInputValue As String
  • Dim sNumberOfGoats As Single
  •  
  • 'Get a value from the user (or a file, a cell, whatevs).
  • tInputValue = InputBox("How many goats?")
  • 'Test whether the value is numeric.
  • If Not IsNumeric(tInputValue) Then
  •     'Do something when the value is not numeric. E.g.:
  •     MsgBox "Sorry, number of goats must be a number."
  •     End
  • End If
  • 'Know that tInputValue has a number.
  • 'This is safe:
  • sNumberOfGoats = tInputValue

This is part of numeric field validation. It's often combined with a range check.

Where referenced