感谢@Tim WIlliams,我有以下代码可以生成插入语句。但是,当我添加以下子程序来调用它来遍历工作簿时,它仍然只拾取活动工作表。我究竟做错了什么?
Sub WorksheetLoop()
Dim WS_Count As Integer
Dim I As Integer
Dim current As Worksheet
' Set WS_Count equal to the number of worksheets in the active
' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count
' Begin the loop.
For Each current In ActiveWorkbook.Worksheets
Call DoSQL
'MsgBox ActiveWorkbook.Worksheets(I).Name
Next
End Sub
Sub DoSQL()
myfile = "test.txt"
fnum = FreeFile()
Open myfile For Output As fnum
Const SQL = "insert into <tbl>(<cols>) values (<vals>)"
Dim dictSQL As Object, rw1 As Range, r As Long, rowSQL
Dim sht As Worksheet, k, c As Range
Dim cols, vals
'Set sht = ActiveSheet
Set rw1 = sht.Range(sht.Cells(1, 1), sht.Cells(1, Columns.Count).End(xlToLeft))
Set dictSQL = tableDict(rw1)
r = 2
Do While sht.Cells(r, 1).Value <> ""
For Each k In dictSQL
rowSQL = Replace(SQL, "<tbl>", k)
cols = ""
vals = ""
For Each c In dictSQL(k).Cells
cols = cols & IIf(Len(cols) > 0, ",", "") & Split(c.Value, ".")(1)
vals = vals & IIf(Len(vals) > 0, ",", "") & _
"'" & Trim(sht.Cells(r, c.Column).Value) & "'"
Next c
rowSQL = Replace(rowSQL, "<cols>", cols)
rowSQL = Replace(rowSQL, "<vals>", vals)
Debug.Print rowSQL
Print #fnum, rowSQL
Next k
r = r + 1
Loop
Close #fnum
End Sub
Function tableDict(rw As Range)
Dim rv As Object, tbl
Set rv = CreateObject("scripting.dictionary")
Dim c As Range
For Each c In rw.Cells
If Len(c.Value) > 0 And InStr(c.Value, ".") > 0 Then
tbl = Split(c.Value, ".")(0) 'table name
If rv.exists(tbl) Then
Set rv(tbl) = Application.Union(c, rv(tbl))
Else
rv.Add tbl, c
End If
End If
Next c
Set tableDict = rv
End Function