Fandom

Visual Basic Wiki

Write Shorter VB Code

66pages on
this wiki
Add New Page
Talk6 Share

Description Edit

This tutorial will show you how to make smaller code to save time.

Make a button disable if a text box is empty Edit

Long Way Edit

If TextBox.Text = "" Then
    Command.Enabled = False
Else
    Command.Enabled = True
End If

Short Way Edit

Command.Enabled = TextBox.Text <> ""

What it means Edit

The long way shows the command button being disabled if the textbox is empty or enabled if it has data in it.

The short way uses simple expressions to achieve the effect in one line. The expression TextBox.Text <> "" means that if the TextBox contains data it returns true and if it doesn't it returns false. Change the enabled to visible if you want to make it invisible instead.

Use IIf Edit

Note of warning: use IIf only when the expressions to be returned are constants; otherwise you will get a performance penalty. If the arguments to IIf are functions or expressions, they will be evaluated, which is especially important to remember if your functions have side effects, a long running time, or if this particular IIf is called a lot, for instance in a loop.

Long Way Edit

Dim RealData, ThisData As Boolean
ThisData = True
If ThisData Then
    RealData = "This data is true"
Else
    RealData = "This data is false"
End If
MsgBox RealData

Short Way Edit

Dim ThisData As Boolean, RealData
ThisData = True
RealData = IIf(ThisData, "This data is true", "This data is false")
MsgBox RealData

What it means Edit

IIf is a function that is used instead of the usual C style "expr ? truePart : falsePart"

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.