利用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

 

posted @ 2015-12-11 17:47  Lio5n  阅读(16654)  评论(0编辑  收藏  举报