使用VBA导入导出csv文件

<导入>

Sub Inport_Renkei_CSV_Click()
    Dim fTextDir As String, rowIndex As Integer, i As Integer
    myFile = Application.GetOpenFilename("連携CSVファイル(*.csv),*.csv")
    If VarType(myFile) = vbBoolean Then
        Exit Sub
    End If
    rowIndex = 1
    Open myFile For Input As #1
    Do While Not EOF(1)
        Line Input #1, currLine
        If rowIndex > 1 Then
        rowDataArr = Split(currLine, Chr(9))
        For i = 0 To UBound(rowDataArr)
            Cells(rowIndex + 1, i + 1).FormulaR1C1 = rowDataArr(i)
        Next i
        End If
        rowIndex = rowIndex + 1
    Loop
    Close #1
    MsgBox "success"
End Sub

<导出>


'根据当前工作簿第二个sheet页的B1单元格,取出第一个sheet页对应的一行数据并出导出csv文件
Sub Export_Renkei_CSV_Click()

    '固定取出49列数据
    Dim Xdata(1 To 49) As Variant, XheadData As Variant     

    Dim ledgerNo As String, addArr() As String
    ledgerNo = Range("B1").Value

    '遍历sheet1的A列,匹配sheet2的B1单元格的值,定位目标数据行
    With Worksheets(1).Range("a:a")
        Set c = .Find(ledgerNo, LookIn:=xlValues)
        '取得固定头数据
        XheadData = Worksheets(1).Range("A2:AW2")
        If Not c Is Nothing Then
            firstAddress = c.Address '结果:$A$5
            addArr = Split(firstAddress, "$")
            nowRow = addArr(2) '得到行5 即第5行数据是需要导出的数据

            For i = 1 To UBound(Xdata, 1)
                Xdata(i) = Worksheets(1).Cells(nowRow, i).Value
            Next i
        End If
    End With

    Dim myFile As Variant
    Dim Fs, downFile As Object

    '遍历数据取得头的csv字符串,以Tab分隔 -> Chr(9)
    headLine = ""
    For i = 1 To UBound(XheadData, 2)

        If headLine = "" Then
            headLine = XheadData(1, i)
        Else
            headLine = headLine & Chr(9) & XheadData(1, i)
        End If
    Next i

    '遍历数据取得内容的csv字符串,以Tab分隔 -> Chr(9)
    dataLine = ""
    For j = 1 To UBound(Xdata)
        If dataLine = "" Then
            dataLine = Xdata(j)
        Else
            dataLine = dataLine & Chr(9) & Xdata(j)
        End If
    Next j

    If VarType(myFile) = vbBoolean Then
        Exit Sub
    End If
    '选择文件下载路径,设置文件名,文件类型
    myFile = Application.GetSaveAsFilename(InitialFileName:=fileName + "_WEBEDI.csv", FileFilter:="連携CSVファイル(*.csv),*.csv")
    'FSO对象引用的后期绑定
    Set Fs = CreateObject("Scripting.FileSystemObject")
    '创建一个文本文件
    Set downFile = Fs.createtextfile(myFile)
    '写入文件内容
    downFile.writeline (headLine)
    downFile.writeline (dataLine)

    MsgBox "success"

End Sub

你可能感兴趣的:(VB)