vb.netで業務効率化を実現!開発者必見の自動化テクニック25選

VB.NET で業務効率化を図るための自動化テクニックを25項目、整理して紹介します。
検索キーワード:「VB.NET 自動化」「業務効率化」「テンプレート生成」などで上位に出るように、実践的なコード例と共に解説します。


1. ファイル・フォルダ操作の自動化

1.1 フォルダの自動作成・削除

Imports System.IO

Public Sub CreateOrDeleteFolder(path As String)
    If Directory.Exists(path) Then
        Directory.Delete(path, True)   ' 再帰的に削除
    Else
        Directory.CreateDirectory(path)
    End If
End Sub
  • 用途:毎日/毎週作業用フォルダを自動で作成し、古いログをクリーンアップ。

1.2 ファイルの一括検索とバックアップ

Public Sub BackupFiles(src As String, dest As String)
    Dim files = Directory.GetFiles(src, "*.txt", SearchOption.AllDirectories)
    For Each f In files
        Dim destPath = Path.Combine(dest, Path.GetFileName(f))
        File.Copy(f, destPath, True)
    Next
End Sub
  • 用途:部署の共通ドキュメントを定期的にバックアップ。

1.3 ディレクトリ内のファイルサイズ統計

Public Function GetTotalSize(folder As String) As Long
    Dim total As Long = 0
    Dim files = Directory.GetFiles(folder, "*", SearchOption.AllDirectories)
    For Each f In files
        total += New FileInfo(f).Length
    Next
    Return total
End Function
  • 用途:ストレージ使用量のレポートを自動で生成。

2. データベース操作の自動化

2.1 バッチ更新クエリ

Public Sub BatchUpdate(tbl As String, updates As Dictionary(Of String, String))
    Using conn As New SqlConnection("your_connection_string")
        conn.Open()
        Dim sb = New StringBuilder()
        sb.Append($"UPDATE {tbl} SET ")
        For Each kv In updates
            sb.Append($"{kv.Key} = @{kv.Key}, ")
        Next
        sb.Length -= 2  ' カンマ削除
        Dim cmd As New SqlCommand(sb.ToString(), conn)
        For Each kv In updates
            cmd.Parameters.AddWithValue($"@{kv.Key}", kv.Value)
        Next
        cmd.ExecuteNonQuery()
    End Using
End Sub
  • 用途:複数レコードに対して一括で値を更新。

2.2 定期レポート出力

Public Function GetMonthlySales(year As Integer, month As Integer) As DataTable
    Dim dt As New DataTable()
    Using conn As New SqlConnection("your_connection_string")
        conn.Open()
        Dim query = "SELECT * FROM Sales WHERE YEAR(Date)=@Y AND MONTH(Date)=@M"
        Using cmd As New SqlCommand(query, conn)
            cmd.Parameters.AddWithValue("@Y", year)
            cmd.Parameters.AddWithValue("@M", month)
            Dim da = New SqlDataAdapter(cmd)
            da.Fill(dt)
        End Using
    End Using
    Return dt
End Function
  • 用途:月次売上レポートを自動生成し、Email で送信。

2.3 データ転送 (ETL) 自動化

Public Sub TransferData(sourceTbl As String, destTbl As String)
    Using source As New SqlConnection("source_conn"), dest As New SqlConnection("dest_conn")
        source.Open()
        dest.Open()
        Dim copyCmd = $"INSERT INTO {destTbl} SELECT * FROM {sourceTbl}"
        Using cmd As New SqlCommand(copyCmd, dest)
            cmd.ExecuteNonQuery()
        End Using
    End Using
End Sub
  • 用途:異なるサーバー間でデータを自動同期。

3. UI 自動化

3.1 Windows フォーム操作自動化(UI Automation)

Imports System.Windows.Automation

Public Sub ClickButton(windowName As String, buttonName As String)
    Dim root = AutomationElement.RootElement
    Dim window = root.FindFirst(TreeScope.Children,
        New PropertyCondition(AutomationElement.NameProperty, windowName))
    If window Is Nothing Then Return

    Dim button = window.FindFirst(TreeScope.Descendants,
        New PropertyCondition(AutomationElement.NameProperty, buttonName))
    Dim invoke = TryCast(button.GetCurrentPattern(InvokePattern.Pattern), InvokePattern)
    invoke?.Invoke()
End Sub
  • 用途:定型作業を手動入力せずに完了。

3.2 フォームデータ自動入力

Imports System.Windows.Forms

Public Sub AutoFill(form As Form, data As Dictionary(Of String, String))
    For Each ctrl In form.Controls.OfType(Of TextBox)()
        If data.ContainsKey(ctrl.Name) Then
            ctrl.Text = data(ctrl.Name)
        End If
    Next
End Sub
  • 用途:複数案件を一括設定。

3.3 スクリーンショット自動取得

Public Sub CaptureScreen(savePath As String)
    Using bmp = New Bitmap(Screen.PrimaryScreen.Bounds.Width,
                           Screen.PrimaryScreen.Bounds.Height)
        Using g = Graphics.FromImage(bmp)
            g.CopyFromScreen(0, 0, 0, 0, bmp.Size)
        End Using
        bmp.Save(savePath)
    End Using
End Sub
  • 用途:ログとして画面状態を定期取得。

4. Web スクレイピングと API 連携

4.1 HtmlAgilityPack を使ったスクレイピング

Imports HtmlAgilityPack

Public Function ScrapeTitle(url As String) As String
    Dim web = New HtmlWeb()
    Dim doc = web.Load(url)
    Return doc.DocumentNode.SelectSingleNode("//title").InnerText
End Function
  • 用途:外部サイトの情報を自動取得。

4.2 REST API 呼び出し

Imports System.Net.Http
Imports Newtonsoft.Json

Public Async Function GetWeather(city As String) As Task(Of String)
    Using client As New HttpClient()
        Dim response = Await client.GetAsync($"https://api.weather.com/{city}")
        Dim json = Await response.Content.ReadAsStringAsync()
        Dim data = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(json)
        Return $"現在の天気: {data("weather")}"
    End Using
End Function
  • 用途:業務上必要な外部情報を取得。

4.3 定期的にデータ取得して DB へ格納

Public Sub SaveWeatherToDB(city As String)
    Dim weather = Await GetWeather(city)
    Using conn As New SqlConnection("your_conn")
        conn.Open()
        Dim cmd = New SqlCommand("INSERT INTO Weather (City,Info,RecordedAt) VALUES (@c,@i,@d)", conn)
        cmd.Parameters.AddWithValue("@c", city)
        cmd.Parameters.AddWithValue("@i", weather)
        cmd.Parameters.AddWithValue("@d", DateTime.Now)
        cmd.ExecuteNonQuery()
    End Using
End Sub
  • 用途:データ分析用の時系列を自動生成。

5. ビルド・CI/CD の自動化

5.1 MSBuild コマンドラインでのビルド

msbuild MyProject.sln /p:Configuration=Release /t:Rebuild
  • VB.NET:ビルドスクリプトをタスクスケジューラに登録し、週次で自動実行。

5.2 GitHub Actions でのワークフロー

name: Build and Deploy
on:
  push:
    branches: [ main ]
jobs:
  build:
    runs-on: windows-latest
    steps:
      - uses: actions/checkout@v2
      - name: Setup .NET
        uses: actions/setup-dotnet@v1
        with: { dotnet-version: '7.0.x' }
      - run: msbuild MyProject.sln /p:Configuration=Release
      - name: Deploy
        run: |
          # Deploy スクリプト
  • 用途:コード変更時に自動デプロイ。

5.3 テスト自動実行(NUnit)

nunit3-console MyTests.dll
  • 用途:CI で毎回テストを走らせ、品質保持。

6. モニタリング・ログ管理

6.1 定期ログファイル削除

Public Sub CleanLogs(logFolder As String, keepDays As Integer)
    Dim files = Directory.GetFiles(logFolder, "*.log")
    For Each f In files
        If File.GetCreationTime(f) < DateTime.Now.AddDays(-keepDays) Then
            File.Delete(f)
        End If
    Next
End Sub
  • 用途:ディスク容量を自動クリア。

6.2 Application Insights への Telemetry 送信

Imports Microsoft.ApplicationInsights
Imports Microsoft.ApplicationInsights.Extensibility

Public Sub TrackEvent(eventName As String, properties As Dictionary(Of String, String))
    Dim telemetry = New TelemetryClient(New TelemetryConfiguration("YOUR_INSTRUMENTATION_KEY"))
    telemetry.TrackEvent(eventName, properties)
End Sub
  • 用途:稼働中の異常を可視化。

6.3 ウィンドウタイトルで監視

Public Sub WatchWindow(title As String)
    Dim root = AutomationElement.RootElement
    Dim w = root.FindFirst(TreeScope.Children,
        New PropertyCondition(AutomationElement.NameProperty, title))
    If w Is Nothing Then
        Console.WriteLine($"{title} が終了しました")
    End If
End Sub
  • 用途:外部アプリが閉じたときに通知。

7. 定型業務のスクリプト化

7.1 Outlook でメール送信

Imports Microsoft.Office.Interop

Public Sub SendMail(recipient As String, subject As String, body As String)
    Dim outApp = New Outlook.Application()
    Dim mail = CType(outApp.CreateItem(Outlook.OlItemType.olMailItem), Outlook.MailItem)
    mail.To = recipient
    mail.Subject = subject
    mail.Body = body
    mail.Send()
End Sub
  • 用途:定期レポート送付を自動化。

7.2 PowerShell スクリプト呼び出し

Public Sub RunPSScript(scriptPath As String)
    Dim psi = New ProcessStartInfo("powershell.exe", $"-File ""{scriptPath}""")
    psi.UseShellExecute = False
    Process.Start(psi)
End Sub
  • 用途:Windows 環境の管理タスクをVBから呼び出す。

7.3 タスクスケジューラからVB.NET を実行

  • schtasks /Create /SC DAILY /TN "MyVBTask" /TR "C:\path\MyApp.exe"

8. コード品質とメンテナンス

8.1 コード生成テンプレート作成

Public Function GenerateCRUDTemplate(tableName As String, columns As List(Of String)) As String
    Dim sb = New StringBuilder()
    sb.AppendLine($"Public Class {tableName}")
    For Each col In columns
        sb.AppendLine($"    Public Property {col} As String")
    Next
    sb.AppendLine("End Class")
    Return sb.ToString()
End Function
  • 用途:DB テーブルに合わせた C# / VB.NET クラスを自動生成。

8.2 静的解析ツール自動走らせる

FxCopCmd.exe /project:MyProject.csproj
  • 用途:ビルド前にコード品質を自動チェック。

8.3 ファイル監視でコード差分を自動レポート

Imports System.IO

Public Sub WatchFolder(path As String)
    Dim watcher = New FileSystemWatcher(path)
    watcher.IncludeSubdirectories = True
    watcher.NotifyFilter = NotifyFilters.LastWrite
    AddHandler watcher.Changed, Sub(sender, e)
                                  Console.WriteLine($"変更: {e.FullPath}")
                               End Sub
    watcher.EnableRaisingEvents = True
End Sub
  • 用途:手動で差分確認する手間を省く。

9. 便利なユーティリティ

ユーティリティ タイプ 使いどころ
CsvHelper ライブラリ CSV への読み書き一括
DocX ライブラリ Word 文書自動生成
SharpZipLib ライブラリ ZIP アーカイブ自動処理
AutoIt スクリプト WinUI 非標準操作補完
Crystal Reports ソフト レポート自動生成
  • これらを組み合わせれば、ファイル/DBレポート生成から UI 連携まで横断的に自動化できます。

10. まとめ

  • ファイル・フォルダの自動作成・削除は、日常的なファイル管理を楽にします。
  • データベース操作は、バッチ更新やレポート生成で作業を大幅に短縮。
  • UI自動化は、手入力を排除して人的ミスを減らします。
  • Web スクレイピング/APIは外部情報をリアルタイムで取得。
  • CI/CDの設定でコード投入ごとに自動テスト・デプロイを実現。
  • モニタリング/ログは運用コストを低減し、障害時の迅速対応を支援。

上記テクニックを 1 つずつ実装し、業務フローに合わせて組み合わせることで、VB.NET での業務効率は格段に向上します。
まずは「今、最も時間がかかっている作業」を洗い出し、そこで使えるテクニックを試してみてください。
自動化は「一つの作業に無駄を削減」するだけでなく、エラー削減品質向上にも直結します。 ぜひ、今日から 1~2 つでも導入してみましょう!

コメント

タイトルとURLをコピーしました