Main Content

Visual Basic フォーム コントロールを使用したユーザー インターフェイスの実装

概要

この例では、スペクトル解析を実行するための包括的な Excel® アプリケーションの作成について説明します。Visual Basic® のフォームとコントロールおよび Excel ワークブックのイベントに関する知識が必要です。これらのトピックについての詳細は、VBA ドキュメンテーションを参照してください。

入力データ セットに高速フーリエ変換 (FFT) を実行してパワー スペクトル密度をプロットする関数を使用する Excel アドインを作成します。関数は入力データに対する FFT の結果、周波数点の配列およびパワー スペクトル密度を返します。次に、現在のワークシート内で入力範囲と出力範囲を指定するフォーム コントロールをもつカスタム VBA マクロを作成します。Excel の [ツール] メニューからスペクトル解析アプリケーションを呼び出します。

アドインを作成するには、以下を行います。

  1. MATLAB® コードから Excel アドインをビルドします。

  2. 入力を収集し、コンポーネントに呼び出しをディスパッチするために必要な VBA コードを実装します。このコードは、Excel にアプリケーションのメニュー項目も作成します。

  3. フォーム コントロールを使用して UI を作成します。

  4. 完成した Excel アドインを保存し、アプリケーションのデプロイに必要なすべてのコンポーネントをパッケージ化します。

Excel アドインを作成する前に、MATLAB Compiler™ Excel ターゲットの要件がすべて満たされていることを確認します。詳細については、MATLAB Compiler での Excel ターゲットの要件と制限を参照してください。

Excel アドインのビルド

  1. MATLAB に付属している xlspectral フォルダーへのパスを保存します。

    copyfile(fullfile(matlabroot,'toolbox','matlabxl','examples','xlspectral'))
  2. MATLAB 関数 computefft.m および plotfft.m を確認します。

     computefft.m

     plotfft.m

  3. ライブラリ コンパイラ アプリまたは compiler.build.excelAddIn を使って、Excel アドインをビルドします。

    以下の情報をプロジェクトに使用します。

    プロジェクト名Fourier
    クラス名Fourier
    コンパイルするファイルplotfft.m

    メモ

    この例において、fourier クラスを使用するアプリケーションは computefft を直接呼び出しません。computefft メソッドは、plotfft メソッドでのみ必要とされます。そのため、関数 computefft は依存関係の分析中にコンパイラによって自動的に含められ、これをパッケージに手動で追加する必要はありません。

    たとえば、compiler.build.excelAddIn を使用している場合は、以下を入力します。

    buildResults = compiler.build.excelAddIn('plotfft.m', ...
    'AddInName','Fourier', ...
    'ClassName','Fourier', ...
    'GenerateVisualBasicFile','on', ...
    'Verbose','on');

    コンポーネントには 1 つのクラスと 2 つのメソッドがあります。

    • computefft — 入力データの FFT とパワー スペクトル密度を計算し、入力されたデータの長さとサンプリング間隔を基に周波数点のベクトルを計算します。

    • plotfftcomputefft と同じ演算を実行し、また、入力データとパワー スペクトル密度を MATLAB Figure ウィンドウにプロットします。

VBA コードの実装

コンポーネントのビルドが終了したら、Excel への統合のために必要な VBA コードを実装します。

メモ

xlspectral フォルダーにある、付属の Excel アドイン Fourier.xla には、既に以下の VBA コードが含まれています。付属のアドインを使用するには、Excel でこれを開き、Excel Visual Basic エディターで "Fourier 1.0 Type Library" および "MWComUtil X.X Type Library" への参照を追加して、アドインを保存します。これで、アドインのテストに進むことができます。

  1. Excel を起動します。

  2. 生成された Excel アドインを開きます。

  3. [開発] タブで [Visual Basic] をクリックするか、ALT + F11 キーを押して [Visual Basic エディター] を開きます。古いバージョンの Excel では、これは [ツール][マクロ][Visual Basic エディター] にある可能性があります。

  4. Visual Basic Editor で、[ツール][参照設定] を選択してプロジェクトの [参照設定] ダイアログ ボックスを開きます。

  5. 生成された Excel アドインに対応する "Fourier 1.0 Type Library" エントリ、および使用しているバージョンの MATLAB または MATLAB Runtime に対応する "MWComUtil X.X Type Library" を選択します。[OK] をクリックして参照を追加します。

メイン VB コード モジュールの作成

関数呼び出し間でアプリケーションの状態を保持するために、アドインには初期化コードとグローバル変数が必要です。これらのタスクを管理するために Visual Basic コード モジュールを実装します。

  1. [モジュール] 下にモジュールがまだ存在していない場合は、プロジェクト ウィンドウで [VBAProject] 項目を右クリックし、[挿入][標準モジュール] を選択します。

    [VBAProject][標準モジュール] の下に新規モジュールが表示されます。

  2. モジュールのプロパティ ページで、Name プロパティを Module1 から FourierMain に変更します。F4 キーを押してプロパティ ウィンドウを表示する必要がある場合もあります。

  3. FourierMain モジュールに以下のコードを入力し、コード ウィンドウを閉じます。

    ' ' FourierMain - Main module stores global state of controls ' and provides initialization code ' Public theFourier As Fourier.Fourier 'Global instance of Fourier object Public theFFTData As MWComplex 'Global instance of MWComplex to accept FFT Public InputData As Range 'Input data range Public Interval As Double 'Sampling interval Public Frequency As Range 'Output frequency data range Public PowerSpect As Range 'Output power spectral density range Public bPlot As Boolean 'Holds the state of plot flag Public theUtil As MWUtil 'Global instance of MWUtil object Public bInitialized As Boolean 'Module-is-initialized flag Private Sub LoadFourier() 'Initializes globals and Loads the Spectral Analysis form Dim MainForm As frmFourier On Error GoTo Handle_Error Call InitApp Set MainForm = New frmFourier Call MainForm.Show Exit Sub Handle_Error: MsgBox (Err.Description) End Sub Private Sub InitApp() 'Initializes classes and libraries. Executes once 'for a given session of Excel If bInitialized Then Exit Sub On Error GoTo Handle_Error If theUtil Is Nothing Then Set theUtil = New MWUtil Call theUtil.MWInitApplication(Application) End If If theFourier Is Nothing Then Set theFourier = New Fourier.Fourier End If If theFFTData Is Nothing Then Set theFFTData = New MWComplex End If bInitialized = True Exit Sub Handle_Error: MsgBox (Err.Description) End Sub

Visual Basic フォームの作成

Visual Basic Editor を使用してアドインのユーザー インターフェイスを開発します。

  1. VBA プロジェクト ウィンドウで [VBAProject] を右クリックし、[挿入][ユーザー フォーム] を順に選択します。

    新規フォームが VBA プロジェクト ウィンドウの Forms の下に表示されます。

  2. フォームのプロパティ ページで、Name プロパティを frmFourier に、Caption プロパティを Spectral Analysis に設定します。

  3. 空白のフォームに以下のコントロールを追加します。

    スペクトル解析用のコントロール

    コントロール タイプコントロール名プロパティ目的

    CheckBox

    chkPlot

    Caption = Plot time domain signal and power spectral density

    入力データとパワー スペクトル密度をプロット。

    CommandButton

    btnOK

    Caption = OK

    Default = True

    関数を実行しダイアログ ボックスを閉じる。

    CommandButton

    btnCancel

    Caption = Cancel

    Cancel = True

    関数を実行せずにダイアログ ボックスを閉じる。

    Frame

    Frame1

    Caption = Input Data

    すべての入力コントロールをグループ化。

    Frame

    Frame2

    Caption = Output Data

    すべての出力コントロールをグループ化。

    Label

    Label1

    Caption = Input Data:

    入力データの RefEdit にラベルを付ける。

    RefEdit

    refedtInput

     

    入力データの範囲を選択。

    Label

    Label2

    Caption = Sampling Interval:

    サンプリング間隔の TextBox にラベルを付ける。

    TextBoxedtSample サンプリング間隔を選択。

    Label

    Label3

    Caption = Frequency:

    周波数出力の RefEdit にラベルを付ける。

    RefEdit

    refedtFreq

     

    周波数点の出力範囲を選択。

    Label

    Label4

    Caption = FFT - Real Part:

    FFT の実数部の RefEdit にラベルを付ける。

    RefEdit

    refedtReal

     

    入力データの FFT の実数部に出力範囲を選択。

    Label

    Label5

    Caption = FFT - Imaginary Part:

    FFT の虚数部の RefEdit にラベルを付ける。

    RefEdit

    refedtImag

     

    入力データの FFT の虚数部に出力範囲を選択。

    Label

    Label6

    Caption = Power Spectral Density

    パワー スペクトル密度の RefEdit にラベルを付ける。

    RefEdit

    refedtPowSpect

     

    入力データのパワー スペクトル密度に出力範囲を選択。

    フォームは以下の図のようになります。ボックス内のテキストは参照用に示したものです。

    Spectral Analysis form

  4. フォームとコントロールが完了したら、フォームを右クリックして [コードの表示] を選択します。

    フォームのコード ウィンドウで、以下のコードを入力します。いずれかのコントロールやグローバル変数に異なる名前を使用した場合は、このコードを変更して相違点を反映させてください。

' 'frmFourier Event handlers ' Private Sub UserForm_Activate() 'UserForm Activate event handler. This function gets called before 'showing the form, and initializes all controls with values stored 'in global variables. On Error GoTo Handle_Error If theFourier Is Nothing Or theFFTData Is Nothing Then Exit Sub 'Initialize controls with current state If Not InputData Is Nothing Then refedtInput.Text = InputData.Address End If edtSample.Text = Format(Interval) If Not Frequency Is Nothing Then refedtFreq.Text = Frequency.Address End If If Not IsEmpty (theFFTData.Real) Then If IsObject(theFFTData.Real) And TypeOf theFFTData.Real Is Range Then refedtReal.Text = theFFTData.Real.Address End If End If If Not IsEmpty (theFFTData.Imag) Then If IsObject(theFFTData.Imag) And TypeOf theFFTData.Imag Is Range Then refedtImag.Text = theFFTData.Imag.Address End If End If If Not PowerSpect Is Nothing Then refedtPowSpect.Text = PowerSpect.Address End If chkPlot.Value = bPlot Exit Sub Handle_Error: MsgBox (Err.Description) End Sub Private Sub btnCancel_Click() 'Cancel button click event handler. Exits form without computing fft 'or updating variables. Unload Me End Sub Private Sub btnOK_Click() 'OK button click event handler. Updates state of all variables from controls 'and executes the computefft or plotfft method. Dim R As Range If theFourier Is Nothing Or theFFTData Is Nothing Then GoTo Exit_Form On Error Resume Next 'Process inputs Set R = Range(refedtInput.Text) If Err <> 0 Then MsgBox ("Invalid range entered for Input Data") Exit Sub End If Set InputData = R Interval = CDbl(edtSample.Text) If Err <> 0 Or Interval <= 0 Then MsgBox ("Sampling interval must be greater than zero") Exit Sub End If 'Process Outputs Set R = Range(refedtFreq.Text) If Err = 0 Then Set Frequency = R End If Set R = Range(refedtReal.Text) If Err = 0 Then theFFTData.Real = R End If Set R = Range(refedtImag.Text) If Err = 0 Then theFFTData.Imag = R End If Set R = Range(refedtPowSpect.Text) If Err = 0 Then Set PowerSpect = R End If bPlot = chkPlot.Value 'Compute the fft and optionally plot power spectral density If bPlot Then Call theFourier.plotfft(3, theFFTData, Frequency, PowerSpect, _ InputData, Interval) Else Call theFourier.computefft(3, theFFTData, Frequency, PowerSpect, _ InputData, Interval) End If GoTo Exit_Form Handle_Error: MsgBox (Err.Description) Exit_Form: Unload Me End Sub

ワークブックへのイベント ハンドラーの追加

  1. VBA プロジェクト ウィンドウで [ThisWorkbook] 項目を右クリックし、[コードの表示] を選択します。

  2. 次のコードを ThisWorkbook に配置します。

    Private Sub Workbook_AddinInstall() 'Called when Addin is installed Call AddFourierMenuItem End Sub Private Sub Workbook_AddinUninstall() 'Called when Addin is uninstalled Call RemoveFourierMenuItem End Sub Private Sub AddFourierMenuItem() Dim ToolsMenu As CommandBarPopup Dim NewMenuItem As CommandBarButton 'Remove if already exists Call RemoveFourierMenuItem 'Find Tools menu Set ToolsMenu = Application.CommandBars(1).FindControl(ID:=30007) If ToolsMenu Is Nothing Then Exit Sub 'Add Spectral Analysis menu item Set NewMenuItem = ToolsMenu.Controls.Add(Type:=msoControlButton) NewMenuItem.Caption = "Spectral Analysis..." NewMenuItem.OnAction = "LoadFourier" End Sub Private Sub RemoveFourierMenuItem() Dim CmdBar As CommandBar Dim Ctrl As CommandBarControl On Error Resume Next 'Find tools menu and remove Spectral Analysis menu item Set CmdBar = Application.CommandBars(1) Set Ctrl = CmdBar.FindControl(ID:=30007) Call Ctrl.Controls("Spectral Analysis...").Delete End Sub

    コードにより、メニュー項目のインストールとアンインストールを行うワークブック イベント AddinInstall および AddinUninstall のイベント ハンドラーが追加されます。メニュー項目は FourierMain モジュール内の関数 LoadFourier を呼び出します。

  3. 終了したら、[保存] アイコンをクリックするか、CTRL + S キーを押してアドインを保存します。

アドインのテスト

アドインを配布する前に、サンプル問題でテストします。スペクトル解析の一般的な利用法は、時間領域のノイズの含まれる信号内に埋もれた信号の周波数成分を見つけることです。2 つの異なる成分を含む信号のデータ表現を作成し、そこにランダムな成分を加えます。このデータは出力と共に Excel ワークシートの列に格納され、パワー スペクトル密度と共に時間領域信号がプロットされます。

テスト問題の作成

  1. Excel の新しいセッションを空のブックで開始します。

  2. [開発] タブで、[Excel アドイン] を選択します。

  3. [アドイン] ダイアログ ボックスで、[参照] をクリックします。

  4. Fourier.xla を参照して、[OK] をクリックします。

    利用可能な [アドイン] リストに、[Spectral Analysis] アドインがチェック ボックスがオンの状態で表示されます。

  5. [OK] をクリックしてアドインを読み込みます。

このアドインは Excel の [アドイン] メニューの下にメニュー項目をインストールします。

データの作成

アドインを呼び出す前に、15 Hz および 40 Hz の成分をもつ信号を含むテスト データを作成します。0.01 秒のサンプリング レートで 10 秒間、信号をサンプリングします。時点を列 A に、信号点を列 B に入力します。

  1. 現在のワークシートのセル A1 に「0」と入力します。

  2. F5 キーまたは CTRL + G キーを押し、[ジャンプ] ダイアログを起動します。参照先 A2:A1001 を追加し、[OK] をクリックしてセルを選択します。

  3. 式「= A1 + 0.01」を入力してから CTRL + Enter キーを押して、選択したセルに式を適用します。

    この手順により、範囲 A1:A1001 には 0 から 10 の区間が 0.01 ずつインクリメントして埋められます。

  4. [ジャンプ] の手順を繰り返し、以下の式を範囲 B1:B1001 の各セルに入力します。

    = SIN(2*PI()*15*A1) + SIN(2*PI()*40*A1) + RAND()

テストの実行

データの列 (列 B) を使用して、アドインをテストします。

  1. Spectral Analysis の UI を表示するには、[アドイン]、[Spectral Analysis] を選択します。

  2. [入力データ] ボックスをクリックします。

  3. 範囲 B1:B1001 をワークシートで選択するか、またはこの範囲を [入力データ] フィールドに入力します。

  4. [Sampling Interval] フィールドに、0.01 を入力します。

  5. [Plot time domain signal and power spectral density] を選択します。

  6. 周波数出力に「C1:C1001」を入力し、同様に FFT 実数部、FFT 虚数部、スペクトル密度に「D1:D1001」、「E1:E1001」および「F1:F1001」を入力します。

  7. [OK] をクリックして解析を実行します。

次の図は、出力の例を示しています。

パワー スペクトル密度では 2 つの信号が 15 Hz および 40 Hz で示されます。