使用VB和macros在Excel中创build查询

我有很多excel中的数据与不同的列。 我的任务是为每一行创build插入语句。 我已经完成了使用Excel的连接function,但我想自动化这个方法。 另一个任务是用''(2个单引号)replace'(单引号),以便可以在sql语句中调整字符。 主要是一次我得到的Excel,我运行我的脚本,将自动作出所有的查询。 之后,我将在SQL开发人员或TOAD中手动运行这些查询。

没有关于你的表格和你的Excel数据的任何信息,这里是一个例子,假设你的excel数据在列A:D从第2行开始,具有与你的表相同的布局。 我也假设你所有的字段都是文本types。

 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 Sub