如何在VBA中的特定行编辑当前存在的.csv文件?

时间:2015-10-14 09:00:43

标签: excel vba excel-vba csv

因此,我尝试在工作簿中编写一些代码,这些代码将使用VBA在某个文件路径中打开文件,查找存在于具有特定行号的行中的数据,然后在给定该行号的情况下覆盖这些行。我知道"打开输入/输出/附加文件"功能但"输入"只读,"输出"覆盖我文件中的所有数据和"追加"仅将数据添加到文件末尾。我已经卡住了一段时间,可以真正使用一些帮助。这是我目前的代码段:

Open Filepath For Output As #2
    ExternalRowCount = 0 ' Row number where I want to start writing data.
    ArrayRef = 0 ' Array Index for data

    Do Until EOF(1)
        ExternalRowCount = ExternalRowCount + 1
        If ExternalRowCount >= Found And ExternalRowCount < (Found + 100) Then ' looping through rows to get to my desired location ("Found" is my desired row number)
            CellData = arr1(ArrayRef)
            CellDataTwo = arr2(ArrayRef)
            Write #2, CellData, CellDataTwo
            ArrayRef = ArrayRef + 1
        End If
    Loop
Close #2

任何帮助将不胜感激!谢谢

1 个答案:

答案 0 :(得分:0)

这将更新Test.csv中的第2行

Option Explicit

Public Sub updateCSVLine()
    Dim fName As String, fso As Object, fsoFile As Object, txt As Variant

    Set fso = CreateObject("Scripting.FileSystemObject")

    Set fsoFile = fso.OpenTextFile("C:\Test.csv", 1)
    txt = fsoFile.ReadAll
    fsoFile.Close

    txt = Split(txt, vbNewLine)

    txt(2 - 1) = ".. valX, .. valY, .. valZ"

    Set fsoFile = fso.OpenTextFile("C:\Test.csv", 2)
    fsoFile.Write Join(txt, vbNewLine)
    fsoFile.Close
End Sub

在:

l1 val1, l1 val2, l1 val3
l2 val1, l2 val2, l2 val3
l3 val1, l3 val2, l3 val3

后:

l1 val1, l1 val2, l1 val3
.. valX, .. valY, .. valZ
l3 val1, l3 val2, l3 val3