在Visual Basic中向csv文件添加一列

时间:2013-03-14 18:00:47

标签: csv vb6

我有什么:

  • .csv文件
  • 有多列
  • 第一栏中的关键字列表

我想做什么:

  • 添加一个新的第一列(移动右边的其他列),我称之为“A”
  • 读取(现在)第二列的每个单词,我称之为“B”
  • 对于列B的每个单词,我想在A列中写出详细的单词

我会处理详细功能。

你可以帮我这个.csv编辑吗?

3 个答案:

答案 0 :(得分:1)

您有第一行关键字:

"B,C,D,E"

但您希望在开头插入"A",例如

"A,B,C,D,E"

您可以阅读整行,并在逗号(,)上拆分。然后在循环中重建字符串,并在索引的特殊情况下使用新关键字。

Dim keywords As String
Dim newKeywords As String
Dim arr() As String
Dim keywordToInsert As String
Dim i As Integer

keywords = "B,C,D,E"
keywordToInsert = "A"

arr = Split(keywords, ",")

For i = 0 To UBound(arr) Step 1
    If i = 0 Then
        newKeywords = keywordToInsert
    End If
    newKeywords = newKeywords & "," & arr(i)
Next i

这会为您提供关键字。使用这个循环,你应该能够提出自己的循环来读取每一行,并像这样操作第一列。

答案 1 :(得分:0)

这假设您知道CSV文件中的列:

Private Sub RewriteFile(ByRef the_sFileName As String)

    Dim sFileNameTemp   As String
    Dim iFileNoInput    As Integer
    Dim iFileNoOutput   As Integer
    Dim iField1         As Integer
    Dim sField2         As String
    Dim datField3       As Date

    ' Temporary file name.
    sFileNameTemp = the_sFileName & ".tmp"

    iFileNoInput = FreeFile
    Open the_sFileName For Input As #iFileNoInput

    iFileNoOutput = FreeFile
    Open sFileNameTemp For Output As #iFileNoOutput

    Do Until EOF(iFileNoInput)
        ' Read in each field of each line into a separate variable, then write to temporary file together with new field. (If you don't know a field's type, use Variants)
        Input #iFileNoInput, iField1, sField2, datField3
        Write #iFileNoOutput, Elaborate(iField1, sField2), iField1, sField2, datField3
    Loop

    Close #iFileNoOutput
    Close #iFileNoInput

    ' Delete the original file, and replace with new file.
    Kill the_sFileName
    Name sFileNameTemp As the_sFileName

End Sub

答案 2 :(得分:0)

或者我可以将原始csv文件上传到数据表中,在表单中的数据网格中将其可视化,然后直接向数据表添加一列