Excelの表を見出しタグ付きHTML形式の表に簡単変換!ユーザー定義関数で実現する方法

Excelの表データをHTML形式のtableタグに変換することはよくある作業ですが、今回はExcelの表を簡単に見出しタグ付きのHTML形式のTABLEタグに変換するユーザー定義関数を紹介します。

ユーザー定義関数の作成

まずは、次のVBAコードを使って、ユーザー定義関数「RangeToHTMLTable」を作成します。

VBAエディタを開き(Alt+F11)、「標準モジュール」へコードを貼り付けてください(挿入→標準モジュール)。

Function RangeToHTMLTable(rng As Range, Optional theadRow As Long = 0, Optional tfootRow As Long = 0, Optional thRow As Long = 0, Optional thCol As Long = 0) As String
Dim output As String
Dim row As Range
Dim cell As Range
Dim rowIndex As Long
Dim colIndex As Long

output = "<table>"

rowIndex = 1
For Each row In rng.Rows
If rowIndex = theadRow Then output = output & "<thead>"
If rowIndex = rng.Rows.Count - tfootRow + 1 Then output = output & "<tfoot>"

output = output & "<tr>"
colIndex = 1
For Each cell In row.Cells
If rowIndex = thRow Or colIndex = thCol Then
output = output & "<th>" & cell.Value & "</th>"
Else
output = output & "<td>" & cell.Value & "</td>"
End If
colIndex = colIndex + 1
Next cell
output = output & "</tr>"

If rowIndex = theadRow Then output = output & "</thead>"
If rowIndex = rng.Rows.Count - tfootRow + 1 Then output = output & "</tfoot>"

rowIndex = rowIndex + 1
Next row

output = output & "</table>"

RangeToHTMLTable = output
End Function

関数の分類の「ユーザー定義」に登録されます。

関数の使い方

次に、作成した「RangeToHTMLTable」関数の使い方を説明します。 この関数は、5つの引数を持ちます。必須の引数は1つだけで、それ以外の引数はすべてオプションです。

    1. rng: HTMLテーブルに変換する範囲
    2. theadRow: 上から何行目をtheadタグとするか(既定値は0)
    3. tfootRow: 下から何行目をtfootタグとするか(既定値は0)
    4. thRow: 上から何行目のセルをすべてthタグとするか(既定値は0)
    5. thCol: 左から何列目のセルをすべてthタグとするか(既定値は0)

基本的な使い方

例えば、A1:C4の範囲にある表をHTMLテーブルに変換するには、次のように入力します。関数リストの「ユーザー定義」に登録されます。

=RangeToHTMLTable(A1:C4)

これにより、A1:C4の範囲がHTMLのtableタグに変換されます。

見出しタグの設定

見出しタグを設定するには、オプション引数を指定します。

例えば、最初の行をtheadタグとして、最後の行をtfootタグとして、最初の列をthタグとする場合は、次のように入力します。

=RangeToHTMLTable(A1:C5, 1, 1, 0, 1)

これにより、最初の行がtheadタグ、最後の行がtfootタグ、最初の列がthタグとなったHTMLテーブルが生成されます。

コメント

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