Visual Basic

#18
TIOBE#8
PYPL#24
IEEESpectrum#28
プログラミング言語MicrosoftWindowsGUIイベント駆動.NET

プログラミング言語

Visual Basic

概要

Visual BasicはMicrosoftが開発したイベント駆動型プログラミング言語で、Windows GUIアプリケーション開発で広く使用されました。

詳細

Visual Basicは1991年にMicrosoftによって発表されたイベント駆動型のプログラミング言語です。BASIC言語をベースとして、視覚的なプログラミング環境(RAD: Rapid Application Development)を提供し、Windows向けのGUIアプリケーションを効率的に開発できるように設計されました。ドラッグ&ドロップによるユーザーインターフェース設計、直感的な構文、豊富なコントロールライブラリにより、プログラミング初心者でも比較的容易にWindowsアプリケーションを作成できました。Visual Basic 6.0(VB6)が最後のクラシック版となり、その後は.NET FrameworkベースのVB.NETに発展しました。現在では新規開発よりもレガシーシステムの保守が中心となっていますが、多くの企業システムで稼働し続けています。

書き方の例

Hello World

' クラシック Visual Basic (VB6) の例
' フォームに配置されたコマンドボタンのクリックイベント
Private Sub Command1_Click()
    MsgBox "Hello, World!"
End Sub

' イミディエイトウィンドウでの実行
' (VBエディタのイミディエイトウィンドウで実行可能)
Sub HelloWorldImmediate()
    Debug.Print "Hello, World!"
End Sub

' プロシージャとして定義
Public Sub HelloWorld()
    MsgBox "Hello, World!", vbInformation, "挨拶"
End Sub

' フォームのLoadイベントでの実行
Private Sub Form_Load()
    Me.Caption = "Hello, World! アプリケーション"
    Label1.Caption = "こんにちは、Visual Basic!"
End Sub

' 複数行のメッセージ
Private Sub ShowMultiLineMessage()
    Dim message As String
    message = "Hello, World!" & vbCrLf & _
              "Visual Basic へようこそ!" & vbCrLf & _
              "GUIアプリケーション開発が簡単です。"
    MsgBox message, vbInformation, "多行メッセージ"
End Sub

' コンソールアプリケーション風の例(実際にはフォーム上のテキストボックス使用)
Private Sub ConsoleStyleHello()
    Text1.Text = Text1.Text & "Hello, World!" & vbCrLf
    Text1.Text = Text1.Text & "現在時刻: " & Now() & vbCrLf
    Text1.Text = Text1.Text & "Visual Basic で作成" & vbCrLf
End Sub

' 入力ダイアログを使った例
Private Sub InteractiveHello()
    Dim userName As String
    userName = InputBox("お名前を入力してください:", "名前入力", "ゲスト")
    
    If userName <> "" Then
        MsgBox "こんにちは、" & userName & "さん!", vbInformation, "個人挨拶"
    Else
        MsgBox "名前が入力されませんでした。", vbExclamation, "警告"
    End If
End Sub

' ループを使った例
Private Sub RepeatedHello()
    Dim i As Integer
    Dim message As String
    
    For i = 1 To 5
        message = message & "Hello " & i & "回目!" & vbCrLf
    Next i
    
    MsgBox message, vbInformation, "繰り返し挨拶"
End Sub

変数とデータ型

' 変数宣言の基本形
Private Sub VariableBasics()
    ' 基本的なデータ型
    Dim studentName As String
    Dim age As Integer
    Dim height As Single
    Dim weight As Double
    Dim isActive As Boolean
    Dim birthDate As Date
    
    ' 値の代入
    studentName = "田中太郎"
    age = 25
    height = 175.5
    weight = 68.5
    isActive = True
    birthDate = #12/25/1998#
    
    ' 宣言と同時に初期化
    Dim score As Integer = 85
    Dim grade As String = "A"
    
    ' 結果の表示
    Debug.Print "名前: " & studentName
    Debug.Print "年齢: " & age
    Debug.Print "身長: " & height & "cm"
    Debug.Print "体重: " & weight & "kg"
    Debug.Print "アクティブ: " & isActive
    Debug.Print "生年月日: " & birthDate
    Debug.Print "スコア: " & score
    Debug.Print "グレード: " & grade
End Sub

' 数値データ型の詳細
Private Sub NumericTypes()
    ' 整数型
    Dim byteValue As Byte        ' 0-255
    Dim integerValue As Integer  ' -32,768 から 32,767
    Dim longValue As Long        ' -2,147,483,648 から 2,147,483,647
    
    ' 浮動小数点型
    Dim singleValue As Single    ' 単精度浮動小数点
    Dim doubleValue As Double    ' 倍精度浮動小数点
    
    ' 通貨型
    Dim currencyValue As Currency ' 固定小数点数値(通貨計算用)
    
    ' 値の設定
    byteValue = 255
    integerValue = -12345
    longValue = 1234567890
    singleValue = 3.14159
    doubleValue = 3.141592653589793
    currencyValue = 1234.56
    
    ' 表示
    Debug.Print "Byte: " & byteValue
    Debug.Print "Integer: " & integerValue
    Debug.Print "Long: " & longValue
    Debug.Print "Single: " & singleValue
    Debug.Print "Double: " & doubleValue
    Debug.Print "Currency: " & Format(currencyValue, "Currency")
End Sub

' 文字列操作
Private Sub StringOperations()
    Dim firstName As String
    Dim lastName As String
    Dim fullName As String
    Dim message As String
    
    firstName = "太郎"
    lastName = "田中"
    
    ' 文字列連結
    fullName = lastName & " " & firstName
    
    ' 文字列関数の使用
    Debug.Print "フルネーム: " & fullName
    Debug.Print "文字数: " & Len(fullName)
    Debug.Print "大文字: " & UCase(fullName)
    Debug.Print "小文字: " & LCase(fullName)
    Debug.Print "左から3文字: " & Left(fullName, 3)
    Debug.Print "右から2文字: " & Right(fullName, 2)
    Debug.Print "3文字目から2文字: " & Mid(fullName, 3, 2)
    
    ' 文字列検索
    If InStr(fullName, "田中") > 0 Then
        Debug.Print "姓は田中です"
    End If
    
    ' 文字列の置換
    message = Replace(fullName, "田中", "佐藤")
    Debug.Print "置換後: " & message
End Sub

' 配列の使用
Private Sub ArrayExamples()
    ' 静的配列
    Dim numbers(1 To 5) As Integer
    Dim fruits(3) As String  ' 0から3まで(4要素)
    
    ' 値の代入
    numbers(1) = 10
    numbers(2) = 20
    numbers(3) = 30
    numbers(4) = 40
    numbers(5) = 50
    
    fruits(0) = "りんご"
    fruits(1) = "バナナ"
    fruits(2) = "オレンジ"
    fruits(3) = "いちご"
    
    ' 動的配列
    Dim scores() As Integer
    ReDim scores(1 To 10)  ' サイズを動的に設定
    
    ' 配列の値を設定
    Dim i As Integer
    For i = 1 To 10
        scores(i) = i * 10
    Next i
    
    ' 配列の内容を表示
    Debug.Print "=== 数値配列 ==="
    For i = 1 To 5
        Debug.Print "numbers(" & i & ") = " & numbers(i)
    Next i
    
    Debug.Print "=== 文字列配列 ==="
    For i = 0 To 3
        Debug.Print "fruits(" & i & ") = " & fruits(i)
    Next i
    
    Debug.Print "=== 動的配列 ==="
    For i = 1 To 10
        Debug.Print "scores(" & i & ") = " & scores(i)
    Next i
    
    ' 配列サイズの変更(データを保持)
    ReDim Preserve scores(1 To 15)
    
    ' 新しい要素に値を設定
    For i = 11 To 15
        scores(i) = i * 5
    Next i
End Sub

' Variantデータ型
Private Sub VariantType()
    Dim varValue As Variant
    
    ' 様々な型の値を格納
    varValue = "文字列"
    Debug.Print "文字列として: " & varValue & " (型: " & TypeName(varValue) & ")"
    
    varValue = 12345
    Debug.Print "数値として: " & varValue & " (型: " & TypeName(varValue) & ")"
    
    varValue = #12/25/2023#
    Debug.Print "日付として: " & varValue & " (型: " & TypeName(varValue) & ")"
    
    varValue = True
    Debug.Print "論理値として: " & varValue & " (型: " & TypeName(varValue) & ")"
    
    ' 配列も格納可能
    Dim tempArray(2) As String
    tempArray(0) = "A"
    tempArray(1) = "B"
    tempArray(2) = "C"
    varValue = tempArray
    Debug.Print "配列として: " & Join(varValue, ",") & " (型: " & TypeName(varValue) & ")"
End Sub

' 定数の使用
Private Sub ConstantExamples()
    ' 定数の宣言
    Const PI As Double = 3.14159265359
    Const COMPANY_NAME As String = "サンプル株式会社"
    Const MAX_USERS As Integer = 100
    
    ' 使用例
    Dim radius As Double
    Dim area As Double
    
    radius = 5
    area = PI * radius * radius
    
    Debug.Print "円の半径: " & radius
    Debug.Print "円の面積: " & area
    Debug.Print "会社名: " & COMPANY_NAME
    Debug.Print "最大ユーザー数: " & MAX_USERS
End Sub

制御構造と関数

' If文とSelect Case文
Private Sub ConditionalStatements()
    Dim score As Integer
    Dim grade As String
    
    score = 85
    
    ' If-ElseIf-Else文
    If score >= 90 Then
        grade = "A"
    ElseIf score >= 80 Then
        grade = "B"
    ElseIf score >= 70 Then
        grade = "C"
    ElseIf score >= 60 Then
        grade = "D"
    Else
        grade = "F"
    End If
    
    Debug.Print "スコア: " & score & ", グレード: " & grade
    
    ' Select Case文
    Select Case score
        Case 90 To 100
            Debug.Print "優秀"
        Case 80 To 89
            Debug.Print "良好"
        Case 70 To 79
            Debug.Print "普通"
        Case 60 To 69
            Debug.Print "要改善"
        Case Else
            Debug.Print "不合格"
    End Select
    
    ' 複数値でのSelect Case
    Dim dayOfWeek As Integer
    dayOfWeek = Weekday(Now)
    
    Select Case dayOfWeek
        Case 1, 7  ' 日曜日、土曜日
            Debug.Print "週末です"
        Case 2 To 6  ' 月曜日から金曜日
            Debug.Print "平日です"
    End Select
End Sub

' ループ構造
Private Sub LoopStructures()
    Dim i As Integer
    Dim j As Integer
    Dim total As Integer
    
    Debug.Print "=== For Next ループ ==="
    For i = 1 To 5
        Debug.Print "カウント: " & i
    Next i
    
    Debug.Print "=== Step付きForループ ==="
    For i = 10 To 2 Step -2
        Debug.Print "逆順: " & i
    Next i
    
    Debug.Print "=== Do While ループ ==="
    i = 1
    Do While i <= 3
        Debug.Print "Do While: " & i
        i = i + 1
    Loop
    
    Debug.Print "=== Do Until ループ ==="
    i = 1
    Do Until i > 3
        Debug.Print "Do Until: " & i
        i = i + 1
    Loop
    
    Debug.Print "=== While Wend ループ ==="
    i = 1
    While i <= 3
        Debug.Print "While Wend: " & i
        i = i + 1
    Wend
    
    Debug.Print "=== ネストしたループ ==="
    For i = 1 To 3
        For j = 1 To 2
            Debug.Print "外側:" & i & ", 内側:" & j
        Next j
    Next i
    
    Debug.Print "=== Exit文の使用 ==="
    For i = 1 To 10
        If i = 5 Then
            Debug.Print "5で終了"
            Exit For
        End If
        Debug.Print "値: " & i
    Next i
End Sub

' 関数とサブプロシージャ
Private Sub ProcedureExamples()
    Dim result As Double
    Dim message As String
    
    ' 関数の呼び出し
    result = CalculateArea(5)
    Debug.Print "半径5の円の面積: " & result
    
    result = AddNumbers(10, 20)
    Debug.Print "10 + 20 = " & result
    
    ' サブプロシージャの呼び出し
    DisplayMessage "こんにちは"
    
    ' 参照渡しの例
    Dim value1 As Integer
    Dim value2 As Integer
    value1 = 10
    value2 = 20
    
    Debug.Print "交換前: value1=" & value1 & ", value2=" & value2
    SwapValues value1, value2
    Debug.Print "交換後: value1=" & value1 & ", value2=" & value2
    
    ' オプション引数の例
    message = CreateGreeting("田中")
    Debug.Print message
    
    message = CreateGreeting("佐藤", "さん")
    Debug.Print message
End Sub

' 面積計算関数
Private Function CalculateArea(radius As Double) As Double
    Const PI As Double = 3.14159265359
    CalculateArea = PI * radius * radius
End Function

' 加算関数
Private Function AddNumbers(num1 As Double, num2 As Double) As Double
    AddNumbers = num1 + num2
End Function

' メッセージ表示サブプロシージャ
Private Sub DisplayMessage(msg As String)
    Debug.Print "メッセージ: " & msg
End Sub

' 値の交換(参照渡し)
Private Sub SwapValues(ByRef a As Integer, ByRef b As Integer)
    Dim temp As Integer
    temp = a
    a = b
    b = temp
End Sub

' オプション引数付きの関数
Private Function CreateGreeting(name As String, Optional suffix As String = "様") As String
    CreateGreeting = "こんにちは、" & name & suffix
End Function

' 可変引数の例(配列を使用)
Private Function SumArray(numbers() As Integer) As Long
    Dim i As Integer
    Dim total As Long
    
    total = 0
    For i = LBound(numbers) To UBound(numbers)
        total = total + numbers(i)
    Next i
    
    SumArray = total
End Function

' エラーハンドリング
Private Sub ErrorHandlingExample()
    On Error GoTo ErrorHandler
    
    Dim result As Double
    Dim num1 As Double
    Dim num2 As Double
    
    num1 = 10
    num2 = 0
    
    Debug.Print "除算を実行します: " & num1 & " ÷ " & num2
    result = num1 / num2  ' ゼロ除算エラーが発生
    Debug.Print "結果: " & result
    
    Exit Sub

ErrorHandler:
    Debug.Print "エラーが発生しました: " & Err.Description
    Debug.Print "エラー番号: " & Err.Number
    
    ' エラーから復帰
    If Err.Number = 11 Then  ' 除算エラー
        Debug.Print "ゼロ除算エラーを検出しました"
        result = 0
        Resume Next
    Else
        Debug.Print "予期しないエラーです"
        Resume ExitPoint
    End If

ExitPoint:
    Debug.Print "プロシージャを終了します"
End Sub

オブジェクト指向とGUI操作

' クラスモジュールの例(別ファイル: Person.cls)
' Class: Person
' プロパティとメソッドを持つクラス

'Private mName As String
'Private mAge As Integer
'Private mEmail As String

' プロパティ(名前)
'Public Property Get Name() As String
'    Name = mName
'End Property

'Public Property Let Name(value As String)
'    mName = value
'End Property

' プロパティ(年齢)
'Public Property Get Age() As Integer
'    Age = mAge
'End Property

'Public Property Let Age(value As Integer)
'    If value >= 0 And value <= 150 Then
'        mAge = value
'    Else
'        Err.Raise 9999, "Person", "年齢は0から150の間で設定してください"
'    End If
'End Property

' プロパティ(メール)
'Public Property Get Email() As String
'    Email = mEmail
'End Property

'Public Property Let Email(value As String)
'    mEmail = value
'End Property

' メソッド
'Public Function Introduce() As String
'    Introduce = "私の名前は" & mName & "で、" & mAge & "歳です。"
'End Function

'Public Sub HaveBirthday()
'    mAge = mAge + 1
'End Sub

' フォームでのクラス使用例
Private Sub ClassUsageExample()
    ' Personクラスのインスタンス作成
    ' Dim person As New Person
    
    ' プロパティの設定
    ' person.Name = "田中太郎"
    ' person.Age = 25
    ' person.Email = "[email protected]"
    
    ' メソッドの呼び出し
    ' Debug.Print person.Introduce()
    ' person.HaveBirthday()
    ' Debug.Print "誕生日後の年齢: " & person.Age
    
    Debug.Print "クラスの例(コメントアウト済み)"
End Sub

' フォームコントロールの操作
Private Sub FormControlExamples()
    ' テキストボックスの操作
    Text1.Text = "Hello, Visual Basic!"
    Text1.ForeColor = vbRed
    Text1.BackColor = vbYellow
    Text1.Font.Size = 12
    Text1.Font.Bold = True
    
    ' ラベルの操作
    Label1.Caption = "現在時刻: " & Format(Now, "yyyy/mm/dd hh:nn:ss")
    Label1.ForeColor = vbBlue
    
    ' コマンドボタンの操作
    Command1.Caption = "クリックしてください"
    Command1.Enabled = True
    
    ' リストボックスの操作
    List1.Clear
    List1.AddItem "項目1"
    List1.AddItem "項目2"
    List1.AddItem "項目3"
    List1.ListIndex = 0  ' 最初の項目を選択
    
    ' コンボボックスの操作
    Combo1.Clear
    Combo1.AddItem "選択肢A"
    Combo1.AddItem "選択肢B"
    Combo1.AddItem "選択肢C"
    Combo1.Text = "選択してください"
    
    ' チェックボックス
    Check1.Caption = "同意する"
    Check1.Value = vbChecked
    
    ' オプションボタン
    Option1.Caption = "男性"
    Option2.Caption = "女性"
    Option1.Value = True
    
    ' ピクチャーボックス
    Picture1.BackColor = vbCyan
    Picture1.BorderStyle = 1  ' 枠線あり
    
    ' フレーム
    Frame1.Caption = "オプション"
End Sub

' イベントプロシージャの例
Private Sub Command1_Click()
    MsgBox "ボタンがクリックされました!", vbInformation, "イベント"
End Sub

Private Sub Text1_Change()
    ' テキストが変更されたときの処理
    Label2.Caption = "文字数: " & Len(Text1.Text)
End Sub

Private Sub List1_Click()
    ' リストボックスの項目がクリックされたときの処理
    If List1.ListIndex >= 0 Then
        Text2.Text = "選択項目: " & List1.List(List1.ListIndex)
    End If
End Sub

Private Sub Form_Load()
    ' フォームが読み込まれたときの処理
    Me.Caption = "Visual Basic サンプル"
    Me.BackColor = vbButtonFace
    
    ' 初期化処理
    FormControlExamples
End Sub

Private Sub Form_Resize()
    ' フォームサイズが変更されたときの処理
    If Me.WindowState <> vbMinimized Then
        ' コントロールのサイズ調整など
        Text1.Width = Me.ScaleWidth - 200
    End If
End Sub

' メニューイベントの例
Private Sub mnuFileOpen_Click()
    ' ファイル→開く メニューの処理
    CommonDialog1.Filter = "テキストファイル (*.txt)|*.txt|すべてのファイル (*.*)|*.*"
    CommonDialog1.ShowOpen
    
    If CommonDialog1.filename <> "" Then
        ' ファイルを開く処理
        Text1.Text = ""
        Open CommonDialog1.filename For Input As #1
        Do Until EOF(1)
            Text1.Text = Text1.Text & Input(1, 1)
        Loop
        Close #1
    End If
End Sub

Private Sub mnuFileSave_Click()
    ' ファイル→保存 メニューの処理
    CommonDialog1.Filter = "テキストファイル (*.txt)|*.txt"
    CommonDialog1.ShowSave
    
    If CommonDialog1.filename <> "" Then
        ' ファイルを保存する処理
        Open CommonDialog1.filename For Output As #1
        Print #1, Text1.Text
        Close #1
        MsgBox "ファイルを保存しました", vbInformation
    End If
End Sub

データベース操作とファイル処理

' ファイル操作の例
Private Sub FileOperations()
    Dim filename As String
    Dim fileContent As String
    Dim lineContent As String
    
    filename = "C:\temp\sample.txt"
    
    ' ファイルに書き込み
    Open filename For Output As #1
    Print #1, "Visual Basic テキストファイル"
    Print #1, "2行目の内容"
    Print #1, "3行目の内容"
    Print #1, "現在時刻: " & Now()
    Close #1
    
    Debug.Print "ファイルを作成しました: " & filename
    
    ' ファイルから読み込み(一括)
    Open filename For Input As #1
    fileContent = ""
    Do Until EOF(1)
        Line Input #1, lineContent
        fileContent = fileContent & lineContent & vbCrLf
    Loop
    Close #1
    
    Debug.Print "=== ファイル内容 ==="
    Debug.Print fileContent
    
    ' ファイルから読み込み(1行ずつ)
    Open filename For Input As #1
    Dim lineNumber As Integer
    lineNumber = 1
    Do Until EOF(1)
        Line Input #1, lineContent
        Debug.Print "行" & lineNumber & ": " & lineContent
        lineNumber = lineNumber + 1
    Loop
    Close #1
    
    ' バイナリファイル操作の例
    Dim binaryFile As String
    Dim byteData As Byte
    
    binaryFile = "C:\temp\binary.dat"
    
    ' バイナリ書き込み
    Open binaryFile For Binary As #1
    For i = 1 To 10
        Put #1, , CByte(i * 10)
    Next i
    Close #1
    
    ' バイナリ読み込み
    Open binaryFile For Binary As #1
    Debug.Print "=== バイナリデータ ==="
    For i = 1 To LOF(1)
        Get #1, i, byteData
        Debug.Print "位置" & i & ": " & byteData
    Next i
    Close #1
End Sub

' INIファイル操作
Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" _
    (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, _
     ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long

Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" _
    (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As String, _
     ByVal lpFileName As String) As Long

Private Sub INIFileOperations()
    Dim iniFile As String
    Dim buffer As String
    Dim result As Long
    
    iniFile = App.Path & "\config.ini"
    
    ' INIファイルに書き込み
    result = WritePrivateProfileString("Settings", "UserName", "田中太郎", iniFile)
    result = WritePrivateProfileString("Settings", "Language", "Japanese", iniFile)
    result = WritePrivateProfileString("Database", "Server", "localhost", iniFile)
    result = WritePrivateProfileString("Database", "Port", "3306", iniFile)
    
    Debug.Print "INIファイルを作成しました: " & iniFile
    
    ' INIファイルから読み込み
    buffer = Space(255)
    result = GetPrivateProfileString("Settings", "UserName", "", buffer, 255, iniFile)
    Debug.Print "ユーザー名: " & Left(buffer, result)
    
    buffer = Space(255)
    result = GetPrivateProfileString("Settings", "Language", "", buffer, 255, iniFile)
    Debug.Print "言語: " & Left(buffer, result)
    
    buffer = Space(255)
    result = GetPrivateProfileString("Database", "Server", "", buffer, 255, iniFile)
    Debug.Print "サーバー: " & Left(buffer, result)
End Sub

' CSV ファイル操作
Private Sub CSVOperations()
    Dim csvFile As String
    Dim csvLine As String
    Dim fields() As String
    Dim i As Integer
    
    csvFile = "C:\temp\data.csv"
    
    ' CSVファイルに書き込み
    Open csvFile For Output As #1
    Print #1, "名前,年齢,部署,給与"
    Print #1, "田中太郎,25,営業部,300000"
    Print #1, "佐藤花子,30,開発部,400000"
    Print #1, "山田一郎,35,管理部,350000"
    Close #1
    
    Debug.Print "CSVファイルを作成しました: " & csvFile
    
    ' CSVファイルから読み込み
    Open csvFile For Input As #1
    
    ' ヘッダー行を読み込み
    Line Input #1, csvLine
    Debug.Print "=== ヘッダー ==="
    Debug.Print csvLine
    
    Debug.Print "=== データ ==="
    Do Until EOF(1)
        Line Input #1, csvLine
        fields = Split(csvLine, ",")
        
        Debug.Print "名前: " & fields(0)
        Debug.Print "年齢: " & fields(1)
        Debug.Print "部署: " & fields(2)
        Debug.Print "給与: " & Format(fields(3), "#,##0") & "円"
        Debug.Print "---"
    Loop
    
    Close #1
End Sub

' レジストリ操作
Private Sub RegistryOperations()
    Dim keyPath As String
    Dim value As String
    
    keyPath = "HKEY_CURRENT_USER\Software\MyApp"
    
    ' レジストリに値を保存
    SaveSetting "MyApp", "Settings", "UserName", "田中太郎"
    SaveSetting "MyApp", "Settings", "LastLogin", CStr(Now())
    SaveSetting "MyApp", "Window", "Width", "800"
    SaveSetting "MyApp", "Window", "Height", "600"
    
    Debug.Print "レジストリに設定を保存しました"
    
    ' レジストリから値を読み込み
    value = GetSetting("MyApp", "Settings", "UserName", "")
    Debug.Print "ユーザー名: " & value
    
    value = GetSetting("MyApp", "Settings", "LastLogin", "")
    Debug.Print "最終ログイン: " & value
    
    value = GetSetting("MyApp", "Window", "Width", "640")
    Debug.Print "ウィンドウ幅: " & value
    
    value = GetSetting("MyApp", "Window", "Height", "480")
    Debug.Print "ウィンドウ高: " & value
    
    ' レジストリから設定を削除
    ' DeleteSetting "MyApp", "Settings", "UserName"
    ' DeleteSetting "MyApp"  ' アプリケーション全体の設定を削除
End Sub

' 簡単なデータベース操作(DAO/ADO)
Private Sub DatabaseOperations()
    ' この例はAccess データベースを使用
    ' 実際の実装では参照設定が必要:
    ' Microsoft DAO 3.6 Object Library または
    ' Microsoft ActiveX Data Objects Library
    
    Debug.Print "データベース操作の例(実装には参照設定が必要)"
    
    ' DAO の例(コメントアウト)
    'Dim db As Database
    'Dim rs As Recordset
    'Dim sql As String
    
    ' データベースを開く
    'Set db = OpenDatabase("C:\temp\sample.mdb")
    
    ' SELECT クエリ実行
    'sql = "SELECT * FROM Users"
    'Set rs = db.OpenRecordset(sql)
    
    ' レコードを読み込み
    'Do Until rs.EOF
    '    Debug.Print rs!UserName & ", " & rs!Age
    '    rs.MoveNext
    'Loop
    
    ' リソースの解放
    'rs.Close
    'db.Close
    'Set rs = Nothing
    'Set db = Nothing
End Sub

メリット・デメリット

メリット

  • 視覚的な開発環境: ドラッグ&ドロップでGUIを簡単に作成可能
  • 学習しやすい構文: BASIC言語ベースで初心者にも理解しやすい
  • 豊富なコントロール: Windows標準のUIコンポーネントが充実
  • RAD(高速アプリケーション開発): プロトタイプから実用アプリまで迅速に開発
  • イベント駆動プログラミング: 直感的なプログラミングモデル
  • Windowsとの親和性: Windows APIや各種コンポーネントとの連携が容易

デメリット

  • レガシー技術: 新規開発での採用は減少傾向
  • プラットフォーム制限: Windowsプラットフォームに依存
  • パフォーマンス: コンパイル済みでも他言語と比較して実行速度が劣る
  • モダンな機能不足: オブジェクト指向の機能が限定的
  • 将来性の懸念: Microsoftのサポート終了やVB.NETへの移行推奨
  • メモリ管理: 手動でのリソース管理が必要な場面あり

主要リンク

公式ドキュメント

学習リソース

開発ツール・環境

移行・代替技術