コーディング · プログラミング言語
Visual Basic .NET入門
結論
Visual Basic .NET(VB.NET)は、.NETプラットフォーム向けのオブジェクト指向・静的型付け言語で、Dim、If ... Then ... End If、For ... Next のような英語に近いキーワードを使います。大文字小文字は区別されず、C#と同じ.NETライブラリを利用できます。プロジェクトは dotnet new console -lang VB で作成し、dotnet run で実行します。Microsoft Office内のマクロ言語であるVBAは、文法のよく似た古い親戚にあたります。
Visual Basic .NETとは何か、誰が使っているのか
VB.NETは、旧来のVisual Basic(VB6)の.NET版後継です。C#と同じ中間言語にコンパイルされるため、2つの言語でライブラリを共有したり、1つのソリューション内で混在させたりできます。主な用途は、Windowsデスクトップアプリ(Windows Forms、WPF)、社内向け業務ツール、ASP.NET Webアプリケーション、そして既存のVBコード資産の保守です。
Microsoftはモダンな.NET上でもVisual Basicのサポートを続けていますが、言語に大きな新機能を加える予定はないと表明しており、.NETの新機能はたいていC#に先に登場します。VBのコード資産がない新規プロジェクトでは、C#のほうが一般的な選択ですが、プログラミングの学習や業務ソフトウェアの開発には、VB.NETも読みやすい言語として今でも使えます。
インストールとHello, world
.NET SDK(Windows、macOS、Linux)をインストールします。WindowsのVisual Studioには、Visual Basicのテンプレートと、ビジュアルなフォームデザイナーも含まれています。
dotnet new console -lang VB -o HelloVB
cd HelloVB
dotnet run
# Hello, world!' Program.vb
Imports System
Module Program
Sub Main(args As String())
Console.WriteLine("Hello, world!")
End Sub
End ModuleModule は共有のプロシージャをまとめ、Sub Main がエントリポイントです。コメントはアポストロフィ ' で始めます。文は通常、行末で終わり、セミコロンや波括弧はありません。
変数と基本の型
変数は Dim name As Type で宣言します。Option Infer On(既定)なら、値を代入するときに型を省略できます。各ファイルの先頭(またはプロジェクト設定)に Option Strict On を指定すると、危険な暗黙の型変換がコンパイルエラーになります。
| 型 | 例 | 備考 |
|---|---|---|
| Integer | Dim n As Integer = 42 | 32ビット。Long は64ビット |
| Double | Dim x As Double = 3.14 | 64ビット浮動小数点数 |
| Decimal | Dim price As Decimal = 19.99D | 正確な10進数。金額向き |
| String | Dim s As String = "hello" | 文字列の連結は & |
| Char | Dim c As Char = "a"c | 1文字。接尾辞は c |
| Boolean | Dim ok As Boolean = True | True / False |
| Date | Dim d As Date = #2026-01-15# | 日付と時刻の値 |
Option Strict On
Module Types
Sub Main()
Dim name As String = "Ana"
Dim age = 30 ' inferred as Integer
Console.WriteLine(name & " is " & age.ToString())
Console.WriteLine($"Next year {name} is {age + 1}")
Console.WriteLine(7 / 2) ' 3.5 (always Double)
Console.WriteLine(7 \ 2) ' 3 (integer division)
Console.WriteLine(7 Mod 2) ' 1
End Sub
End Module制御構文
Dim score = 85
If score >= 90 Then
Console.WriteLine("A")
ElseIf score >= 80 Then
Console.WriteLine("B")
Else
Console.WriteLine("C")
End If
Select Case score
Case 90 To 100
Console.WriteLine("excellent")
Case 80 To 89
Console.WriteLine("good")
Case Else
Console.WriteLine("keep going")
End Select
For i = 1 To 3
Console.WriteLine($"{i} squared is {i * i}")
Next
Dim n = 3
Do While n > 0
n -= 1
Loopこれらの文は Sub の中に書きます。For i = 1 To 3 は両端を含みます。カウントダウンするには Step -1 を付けます。For Each item In collection は任意のコレクションを走査します。ループを途中で抜けるには Exit For や Exit Do を使います。条件式には AndAlso と OrElse を使うのがお勧めです。結果が決まった時点で評価を打ち切る一方、And と Or は常に両辺を評価します。
SubとFunction、ラムダ式
Sub は値を返さず、Function は値を返します。引数は既定で ByVal(コピー)で渡され、ByRef を使うと呼び出し元の変数をプロシージャ側で変更できます。引数は既定値付きで Optional にもできます。
Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function
Sub Greet(Optional name As String = "world")
Console.WriteLine($"Hello, {name}!")
End Sub
Sub Increment(ByRef value As Integer)
value += 1
End Sub
' Inside Sub Main:
Dim x = 5
Increment(x) ' x is now 6
Greet() ' Hello, world!
Dim square = Function(n As Integer) n * n ' lambda
Console.WriteLine(square(Add(1, 2))) ' 9配列、List、Dictionary
Dim nums() As Integer = {3, 1, 2}
Dim five(4) As Integer ' 5 elements, indexes 0 to 4
Array.Sort(nums)
Console.WriteLine(String.Join(", ", nums)) ' 1, 2, 3
Dim names As New List(Of String) From {"Ana", "Ben"}
names.Add("Cleo")
Console.WriteLine(names.Count) ' 3
Dim ages As New Dictionary(Of String, Integer)
ages("Ana") = 30
ages("Ben") = 17
For Each pair In ages
Console.WriteLine($"{pair.Key}: {pair.Value}")
Next配列とリストは0から始まり、添字は丸括弧で書きます(nums(0))。ジェネリック型には Of を使い、List(Of String) はC#の List<string> に当たるVBの書き方です。なお、Dim five(4) が宣言するのは長さではなく上限の添字なので、要素数は5つになります。
VBならではの機能:クラス、プロパティ、LINQクエリ
VB.NETは完全なオブジェクト指向で、クラスにはプロパティ、メソッド、コンストラクタ(Sub New)、継承(Inherits)、インターフェイス(Implements)、イベント(Event、RaiseEvent、Handles)があります。LINQクエリは読みやすいクエリ構文で書けます。
Public Class Person
Public Property Name As String
Public Property Age As Integer
Public Sub New(name As String, age As Integer)
Me.Name = name
Me.Age = age
End Sub
End Class
' Inside Sub Main:
Dim people As New List(Of Person) From {
New Person("Ana", 30),
New Person("Ben", 17)
}
Dim adults = From p In people
Where p.Age >= 18
Select p.Name
For Each adultName In adults
Console.WriteLine(adultName) ' Ana
NextVBは大文字小文字を区別しないため、Name と name は同じ識別子です。コンストラクタの中では、Me.Name がプロパティを、name が引数を指します。ほかにも、With ... End With ブロック、XMLリテラル、よく使う処理をまとめた My 名前空間といった、VB固有の便利機能があります。
エラー処理
VB.NETは構造化例外処理(Try、Catch、Finally、Throw)を使います。Catch には When フィルターも付けられます。VB6やVBAで使われた古い On Error GoTo 形式もコンパイルは通りますが、新しい.NETコードでは使わないでください。
Function ParseAge(s As String) As Integer
Dim n As Integer
If Not Integer.TryParse(s, n) Then
Throw New FormatException($"Not a number: {s}")
End If
If n < 0 Then Throw New ArgumentOutOfRangeException(NameOf(s))
Return n
End Function
' Inside Sub Main:
Try
Console.WriteLine(ParseAge("abc"))
Catch ex As FormatException
Console.WriteLine("Error: " & ex.Message) ' Error: Not a number: abc
Finally
Console.WriteLine("done")
End Try小さな完成プログラム:単語の出現頻度
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module WordCount
Sub Main()
Dim text = "the cat and the hat and the bat"
Dim counts As New Dictionary(Of String, Integer)
For Each word In text.Split(" "c)
If counts.ContainsKey(word) Then
counts(word) += 1
Else
counts(word) = 1
End If
Next
Dim top = counts.OrderByDescending(Function(kv) kv.Value).Take(2)
For Each kv In top
Console.WriteLine($"{kv.Key} {kv.Value}")
Next
End Sub
End Module
' the 3
' and 2VBA:Microsoft Office内のVisual Basic
Visual Basic for Applications(VBA)は、Excel、Word、AccessなどのMicrosoft Officeアプリに組み込まれたマクロ言語です。.NETではなく旧来のVisual Basicをベースにしており、Officeアプリの内部で動作し、Officeのオブジェクトモデル(ブック、セル範囲、ドキュメント)を使い、VBAエディター(Windowsでは Alt+F11)で編集します。Dim、If、For、Sub といった基本文法は共通なので、VB.NETの知識はVBAにも役立ちます。
' VBA in Excel: write the squares of 1 to 5 into column A
Sub FillSquares()
Dim i As Long
For i = 1 To 5
Cells(i, 1).Value = i * i
Next i
MsgBox "Done"
End Sub次のステップ
- Microsoft Learn:Visual Basicのドキュメント(入門ガイドと言語リファレンスを含む)。
- .NETの基本クラスライブラリ(コレクション、ファイル、LINQ)を学びましょう。C#と共通です。
- デスクトップアプリなら、Visual StudioでWindows FormsやWPFのテンプレートを試してみましょう。
- Officeの自動化なら、使っているアプリのVBAリファレンスをMicrosoft Learnで読みましょう。
よくある質問
Visual Basic .NETはもう終わった言語ですか?
いいえ。現行の.NETバージョンとVisual Studioでサポートされています。ただしMicrosoftは言語への大きな新機能を予定していないため、新しい.NETプロジェクトの多くはC#を選びます。
VB.NETとVBAの違いは何ですか?
VB.NETは、単体のアプリケーションを作るための本格的な.NET言語です。VBAは旧来のVisual Basicをベースにしたマクロ言語で、ExcelなどのOfficeアプリの内部で動きます。文法は似ていますが、ランタイムとライブラリは異なります。
VB.NETとC#はどちらを学ぶべきですか?
VBのコードを保守している場合や、とても読みやすい文法が好みなら、VB.NETで問題ありません。新規プロジェクト、求人、最新の.NET機能を考えるなら、通常はC#のほうが良い投資になり、学んだライブラリはどちらの言語にも通用します。
Visual Basicは大文字小文字を区別しますか?
いいえ。Dim Total、total、TOTAL はすべて同じ変数を指し、エディターが大文字小文字を自動で整えてくれるのが普通です。