0
0

AccessでWebビューアプリ

Posted at

はじめに

「Accessでアプリを作る」という縛りがある中、古臭くないUIを求められたので、
AccessをベースとしたWebビューアプリに仕立ててみました。

サンプルではhtmlファイルを外出しにしていますが、テキストデータとしてAccess側に埋め込むことも出来ます。
メンテナンス性が悪くなりますが…

使用する「Microsoft Web Browser」はベースがIEです。
その為、cssやjavascriptはIEに対応した書き方にする必要があります。

手順(サンプル)

1. Accessファイル(サンプルではファイル名:AccessHtml.accdb)を作成します

2. フォーム(サンプルではフォーム名:frmBrowser)を追加します

3. フォームに「Microsoft Web Browser」(サンプルではオブジェクト名:webBrowser)を追加します

4. フォームにボタン(サンプルではオブジェクト名:btnToHtml)を追加します

5. 参照設定に「Microsoft HTML Object Library」を追加します

6. VBA(Form_frmBrowser)に以下を記述します

Form_frmBrowser
Option Compare Database

Private WithEvents htmlCmd As MSHTML.HTMLInputButtonElement
Private WithEvents accessCmd As MSHTML.HTMLInputButtonElement
Private WithEvents linkVal As MSHTML.HTMLInputTextElement

Private Sub Form_Load()
    'フォームロード時にhtmlファイルを読み込む
    webBrowser.Navigate CurrentProject.Path & "\Sample.html"
End Sub

Private Sub webBrowser_DocumentComplete(ByVal pDisp As Object, URL As Variant)
    'htmlファイルの読み込み後に実行される
    'html側のonloadで実行した処理と非同期で実行される
    '実行する順序が重要になる場合は注意が必要
    Call connectBrowser
End Sub

Private Sub webBrowser_BeforeScriptExecute(ByVal pDispWindow As Object)
    'htmlファイルのscriptタグが読み込まれる前に実行される
    '「セキュリティ保護のため、~」が表示されてる。
    'ブロックされているコンテンツを許可した場合にリロードがかかるが、
    'その際にDocumentCompleteが呼ばれないため、ここでも実行する
    Call connectBrowser
End Sub

Private Sub connectBrowser()
    'html側のelementをVBAのオブジェクトにセットする
    Set htmlCmd = webBrowser.Document.all.btnHtml
    Set accessCmd = webBrowser.Document.all.btnAccess
    Set linkVal = webBrowser.Document.all.txtVal
End Sub

Private Sub btnToHtml_Click()
    linkVal.Value = "accessからjavascriptの処理を実行しました。"
    '⇒html側のtxtValに値が入る
    
    htmlCmd.Click
    '⇒html側のbtnHtmlのクリックイベントが実行される
End Sub

Private Function AccessCmd_onclick() As Boolean
    MsgBox linkVal.Value
End Function

7. htmlファイル(サンプルではファイル名:Sample.html)をAccessファイルと同じフォルダ内に作成します

8. html(Sample.html)に以下を記述します

Sample.html
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  </head>
  <body>
    <input type="hidden" id="txtVal">
    <input type="hidden" id="btnAccess">
    <input type="hidden" id="btnHtml" onclick="fromAccess();">
    <button id="btnSet" onclick="toAccess();">Accessの処理を実行</button>
  </body>
  <script type="text/javascript">
    function fromAccess() {
      alert(document.getElementById('txtVal').value);
    }
    
    function toAccess() {
      document.getElementById('txtVal').value = 'javascriptからaccessの処理を実行しました。';
      //⇒Access側のlinkValに値が入る
      
      document.getElementById('btnAccess').click();
      //⇒Access側のAccessCmd_onclickイベントが実行される
    }
  </script>
</html>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0