0
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.

INSERT文作成マクロ

Last updated at Posted at 2020-01-14
insert.vba
Option Explicit

Sub MakeInsert()

Dim sqlstring As String
Dim colindex As Integer

Dim sqlcolumns As String
Dim maxcol As Integer

Const Phrase1 As String = "INSERT INTO "
Const Phrase2 As String = " ("
Const Phrase3 As String = ") VALUES ("
Const Phrase4 As String = ");"

'SQLシートをクリア
SQL.Cells.Clear

'テーブル名を取得
sqlstring = Phrase1 + DATA.Range("B3") + Phrase2

'カラム行の終わりを取得
maxcol = Range("B6").End(xlToRight).Column

'1カラムだけだと16384が返ってくるので2を無理やり代入
If maxcol = 16384 Then

  maxcol = 2
  
End If

'カラム数だけ回してカラム定義部分を作成
'カラムが入っているのが2列目なので2からmaxcolまで
For colindex = 2 To maxcol

  sqlcolumns = sqlcolumns + DATA.Cells(6, colindex)
  
  If colindex <> maxcol Then
    sqlcolumns = sqlcolumns + ", "
  Else
  ' カラム定義の最後尾の処理
    sqlcolumns = sqlcolumns + Phrase3
  End If
Next

'INSERT文のカラム部分をVALUEの手前まで作成する
sqlstring = sqlstring + sqlcolumns


Dim maxrow As Integer
'値が入っている最後の行数を取得
maxrow = Range("B6").End(xlDown).row

Dim rows As Integer
Dim cols As Integer
Dim valuestring As String
'値を入れてSQLを作成
'行数分だけ回す。値の入っているのが7行目からなので7からmaxrowまで
For rows = 7 To maxrow
  'カラムの数だけ回す
  For cols = 2 To maxcol
  
    If IsEmpty(DATA.Cells(rows, cols)) = True Then
      '空白の時はnull扱い
      valuestring = valuestring + "null"
    Else
      '文字列の時はシングルクォーテーションで囲む
      If TypeName(DATA.Cells(rows, cols).Value) = "String" Then
        valuestring = valuestring + "'" + DATA.Cells(rows, cols) + "'"
      Else
      'それ以外は文字列に変換
        valuestring = valuestring + CStr(DATA.Cells(rows, cols))
      End If
    End If
    
    If cols <> maxcol Then
      valuestring = valuestring + ","
    End If
    
  Next
  
  SQL.Cells(rows, 2) = sqlstring + valuestring + Phrase4
  valuestring = ""
Next

End Sub


0
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
0
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?