Skip to content

Instantly share code, notes, and snippets.

@harapeko
Created June 4, 2014 17:03
Show Gist options
  • Save harapeko/4e8f5e349e4bf6837a91 to your computer and use it in GitHub Desktop.
Save harapeko/4e8f5e349e4bf6837a91 to your computer and use it in GitHub Desktop.
ヾ(o゚ω゚o)ノ゙INSERT文をExcelデータから出力するマン! ref: http://qiita.com/harapeko_wktk/items/47781423d6836234a43b
Dim hogehoge As String
INSERT INTO tbl_name (date, point)
VALUES
('2014-05-02', 1.7),
('2014-05-03', 2.2),
('2014-05-04', 3.4),
('2014-05-05', 0.4);
Option Explicit
Sub INSERT文を生成_Click()
'現在シート
Dim ws As Worksheet
Set ws = ActiveSheet
'sql保存用
Dim sql As String
sql = ""
'INSERT INTO シート名
Dim head As String
head = "INSERT INTO " & ws.Name & vbLf
'COLUMNSの箇所
Dim cols As String
cols = ""
'VALUESの箇所
Dim values As String
values = ""
'使用しているセルの範囲を取得
Dim target As Range
Set target = ws.UsedRange
'現在セル用の変数
Dim currentCell As Range
Dim i As Integer
'カラム名を取得
For i = 1 To target.Rows.Count
If (i <> 1) Then
cols = cols & ", "
End If
Set currentCell = ws.Cells(i, 1)
cols = cols & currentCell.Value
Next
cols = "(" & cols & ")"
'VALUESを取得
Dim j As Integer
Dim strtmp As String
For j = 2 To target.Columns.Count
'非表示の列があったらスキップ
If Columns(j).Hidden Then GoTo Next_ColumnLoop
If (j = 2) Then
values = values & "("
ElseIf (j >= 2) Then
values = values & "," & vbLf & "("
End If
For i = 1 To target.Rows.Count
If (i <> 1) Then
values = values & ", "
End If
Set currentCell = ws.Cells(i, j)
If (IsNull(currentCell) Or currentCell.Value = "" Or Trim(currentCell.Value) = "null") Then
'null
values = values & "null"
ElseIf IsNumeric(currentCell.Value) Then
'数値
values = values & currentCell.Value
ElseIf Left(currentCell.Value, 8) = "(SELECT " Then
'SQL
values = values & currentCell.Value
Else
'文字列はシングルクォーテーションをエスケープする
strtmp = Replace(currentCell.Value, "'", "''")
'セル内の改行を改行コードに変換
strtmp = Replace(strtmp, vbLf, "' || CHR(13) || CHR(10) ||'")
values = values & "'" & strtmp & "'"
End If
Next
values = values + ")"
Next_ColumnLoop:
Next
'SQL文完成!
sql = head & cols & vbLf & "VALUES" & vbLf & values & ";"
Dim cb As New DataObject
With cb
.SetText sql
.PutInClipboard
End With
MsgBox ("クリップボードにコピーしました")
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment