2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

VBAマクロ insert文自動生成

Posted at

本記事は、マクロを用いて、insert文を大量に自動作成する技術投稿記事になります。

パフォーマンス的にはsqlloaderを使用するほうが圧倒的に早いですが、本記事にて生成するsqlファイルはinsert文としてコピペしてそのまま使用可能なため、可視性に優れているという利点があります。

以下に手順を記載します。
1.ボタンを配置したシートのB2セルに、出力対象シート名を記入する。
2.出力対象シートに、作成するデータを設定する。
3.マクロを作成する。
4.マクロを実行する。

1.ボタンを配置したシートのB2セルに、出力対象シート名を記入する。
 下記のようなイメージです。
image.png

 今回はm_table1のシートデータをこのファイル名で出力します。
 ボタンを配置する当シート名は何でも良いです。

2.出力対象シートに、作成するデータを設定する。
 下記のようなイメージです。

image.png

 B列をファイル出力します。
 D列~J列はm_table1_dataシートの実際のデータを加工しています。
 C列でCONCATし、B列でA1及びA2セルとC列のセルを合わせています。

 下記がデータシートのサンプルです。

image.png

3.マクロを作成する。
 以下のプログラムを作成します。

Sub createInsertSql()
 Dim workfile As String, sheetName As String, r As Integer, ws As Worksheet, wsExistFlg As Boolean, wfOpenedFlg As Boolean

 sheetName = "" Then
  MsgBox "対象シートを黄色セル(B2)に入力して下さい。"
  End
 End If

 wsExistFlg = isSheetExist(sheetName)

 If wsExistFlg = False Then
  MsgBox "対象シートを正しく入力して下さい。"
 End If

 workfile = ActiveWorkbook.Path & "\insert_" & sheetName & ".sql"
 wfOpenedFlg = isWorkfileOpened(workfile)

 If wfOpenedFlg = True Then
  MsgBox "出力対象のファイルが開かれているため、書き込めません。"
 End If

 Open workfile For Output As #1

 r = 2

 Set ws = Sheets(sheetName)

 Do While ws.Cells(r, 2).Value <> ""
  Print #1, ws.Cells(r, 2).Value
  r = r + 1
 Loop
 Close #1

 MsgBox "作成完了しました。"
End Sub

Function isSheetExist(ByVal sheetName As String) As Boolean
 Dim ws As Worksheer
 isSheetExist = False
 For Each ws In Worksheets
  If ws.name = sheetName Then is SheetExist = True
 Next ws
End Funtion

Function isWorkfileOpened(ByVal workfileName As String) As Boolean
 isWorkfileOpened = False

 On Error Resume Next

 Open workfileName For Output As #1
 Close #1

 If Err.Number > 0 Then
  isWorkfileOpened = True
 End If
End Function

使用する際は、createInsertSql()をボタン等に設定してご使用下さい。

4.マクロを実行する。
 ボタンを押すだけ。
 以下のような内容で出力されます。
image.png

以上になります。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?