利用VBA遍历Excel所有sheet的例子

下面是利用VBA遍历Excel sheet的例子,可以用于Excel的批量处理。

Sub Insert_CodeString()

Dim fs, ft As Object
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet

Dim Sql As String
    Sql = "truncate table code_string;" & Chr(10)
Dim line As Integer

Set fs = CreateObject("scripting.filesystemobject")
Set ft = fs.createtextfile(ThisWorkbook.Path & "" & "Insert_CodeString" & ".sql")

Set xlBook = ThisWorkbook


For x = 1 To xlBook.Sheets.Count

    Set xlSheet = xlBook.Sheets(x)
    
    If xlSheet.Cells(3, 1) = "代码编号" Then

        line = 8
        Sql = Sql & Chr(10) & Chr(10) & "--" & xlSheet.Cells(4, 2) & Chr(10)
        
        Do
            Sql = Sql & "Insert Into CODE_STRING ( CODE_TYPE,CODE_TYPE_DESC,CODE_VALUE,CODE_DESC,CODE_FLAG ) Values ( '" & xlSheet.Cells(3, 2) & "','" & xlSheet.Cells(4, 2) & "','" & xlSheet.Cells(line, 2) & "','" & xlSheet.Cells(line, 3) & "','1');" & Chr(10)
            line = line + 1
        Loop Until Len(xlSheet.Cells(line, 1).Value) = 0
        
    End If
    
Next x

Sql = Sql & Chr(10) & Chr(10) & "commit;" & Chr(10)

ft.WriteLine (Sql)
ft.Close

Set ft = Nothing: Set fs = Nothing

End Sub
原文地址:https://www.cnblogs.com/wanggs/p/5039778.html