我在excel中有很多不同列的数据。我的任务是为每一行创建insert语句。我已经使用了excel的拼接函数,但我想自动化这个方法。另一项任务是将‘(单引号)替换为''(2个单引号),以便可以在sql语句中调整字符。主要是一旦我得到了excel,我运行我的脚本,它将自动进行所有的查询。然后,我将在SQL developer或TOAD中手动运行这些查询。
发布于 2017-02-28 15:39:23
在没有任何关于您的表和Excel数据的信息的情况下,这里有一个示例,假设您的excel数据位于从第2行开始的列A:D中,其布局与您的表相同。我还假设您的所有字段都是文本类型。
Sub createQueries()
Dim r As Range, cel As Range, record As String
'Get the range to export
With Sheet1
Set r = .Range("A2:D" & .Range("D999999").End(xlUp).Row)
End With
' Create a text file for the query
With CreateObject("Scripting.FileSystemObject").CreateTextFile("c:\SO\queries.txt")
For Each r In r.Rows
' create an Insert line into the query
record = "INSERT INTO MYTABLE (""FieldA"", ""FieldB"", ""FieldC"", ""FieldD"") Values ("
For Each cel In r.Cells
record = record & "'" & Replace(cel.Text, "'", "''") & "',"
Next
record = Left(record, Len(record) - 1) & ");"
.WriteLine record
Next
.Close
End With
End Subhttps://stackoverflow.com/questions/42501968
复制相似问题