1. 程式人生 > >使用VBA匯入匯出csv檔案

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