csv macro

Option Explicit


Const DB_COLUMN_ROW As Integer = 1
Const DB_DATA_ROW As Integer = 3
Const DB_START_COLUMN As Integer = 1


Sub ExportCsv()
    On Error GoTo ERR_LINE
    
    Dim columnIndex As Integer
    Dim c As Range
    Dim csvHead As String
    Dim table As String
    
    columnIndex = DB_START_COLUMN
    
    Set c = Cells(DB_COLUMN_ROW, columnIndex)
    table = UCase(c.Comment.Text)
    
    While Trim(c.Value) <> ""
        csvHead = csvHead & UCase(Trim(c.Value)) & ","
        columnIndex = columnIndex + 1


        Set c = Cells(DB_COLUMN_ROW, columnIndex)
    Wend


    columnIndex = columnIndex - 1
    
    Dim csvNo As Long
    Dim csv As String
    csv = ThisWorkbook.Path & "\" & table & ".csv"
    
    csvNo = FreeFile
    Open csv For Output Access Write As #csvNo
    
    csvHead = Left(csvHead, Len(csvHead) - 1)
    Print #csvNo, csvHead
    
    Dim row As Integer
    row = DB_DATA_ROW
    Set c = Cells(row, DB_START_COLUMN)
    
    Dim i As Integer
    Dim dl As String
    
    While Trim(c.Value) <> ""
        dl = ""
        For i = DB_START_COLUMN To columnIndex
            dl = dl & "'" & Trim(Cells(row, i).Value) & "',"
        Next i
        
        dl = Left(dl, Len(dl) - 1)
        Print #csvNo, dl
        
        row = row + 1
        Set c = Cells(row, DB_START_COLUMN)
    Wend
    
    
    Debug.Print csvHead
    Debug.Print table
    
    Close #csvNo
    
    MsgBox "done"
    
    Exit Sub
    
ERR_LINE:
    MsgBox Err.Description, vbCritical + vbYesNo, "Error"
    If csv <> 0 Then
        Close #csvNo
    End If
End Sub

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值