感謝@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
我已經編輯了我的原始答案以添加循環... – 2013-02-26 18:57:33
我解決了這個問題。我錯過了 For Each current In Application.Worksheets current.Activate – 2013-02-26 18:59:53
@TimWilliams再次感謝你 – 2013-02-26 19:01:05