在CSV文件VBA中选择特定行

时间:2018-01-29 09:11:56

标签: excel vba excel-vba csv

这个问题与my previous question有关。毕竟,所需要的只是删除尾随“;”在特定的行(1,2,最后一行和之前的行),所以我想知道是否有办法在CSV中选择行,以便我可以在这些特定的行上使用我的函数。

我现在所拥有的并得到了我之前问题的解决方案:

Option Explicit
Public Function RemoveTrailing(s As String) As String
  Dim nIndex As Integer

  For nIndex = Len(s) To 1 Step -1
    If Right$(s, 1) = ";" Then
      s = Left$(s, Len(s) - 1)
    End If
  Next
  RemoveTrailing = s

End Function

Sub ExportAsCSV()

    Dim MyFileName As String
    Dim CurrentWB As Workbook, TempWB As Workbook

    Set CurrentWB = ActiveWorkbook
    ActiveWorkbook.ActiveSheet.UsedRange.Copy

    Set TempWB = Application.Workbooks.Add(1)
    With TempWB.Sheets(1).Range("A1")
        .PasteSpecial xlPasteValues
        .PasteSpecial xlPasteFormats
    End With

    MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"

    Application.DisplayAlerts = False
    TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
    TempWB.Close SaveChanges:=False
    Application.DisplayAlerts = True
    Dim sFile2 As String
    Dim sLine As String

    sFile2 = Replace(MyFileName, ".csv", "SANS_VIDE.csv")
    Open MyFileName For Input As #1
    Open sFile2 For Output As #2

    Do Until EOF(1)
        Line Input #1, sLine
        Print #2, RemoveTrailing(sLine)
    Loop

    Close #1
    Close #2
End Sub

我需要的不是循环:

Do Until EOF(1)
            Line Input #1, sLine
            Print #2, RemoveTrailing(sLine)
        Loop

仅在第一行,第二行,最后一行和前一行应用“RemoveTrailing”功能。

我该怎么做?我是VBA的新手。

1 个答案:

答案 0 :(得分:0)

执行此操作的一种方法是了解文件中存在多少行,因此请先读取并计算它们。然后当你写作时,如果你输出的行是第1,第2,倒数第二或最后一行,请执行RemoveTrailing

试试这个:

Sub ExportAsCSV()

Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook

Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy

Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
    .PasteSpecial xlPasteValues
    .PasteSpecial xlPasteFormats
End With

MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"

Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
Dim sFile2 As String
Dim sLine As String

sFile2 = Replace(MyFileName, ".csv", "SANS_VIDE.csv")

Dim rowcount As Long, thisrow As Long

Open MyFileName For Input As #1
rowcount = 0
Do Until EOF(1)
    Line Input #1, sLine
    rowcount = rowcount + 1
Loop
Close #1

Open MyFileName For Input As #1
Open sFile2 For Output As #2
thisrow = 0
Do Until EOF(1)
    thisrow = thisrow + 1
    Line Input #1, sLine
    If thisrow <= 2 Or thisrow >= rowcount - 1 Then
        Print #2, RemoveTrailing(sLine)
    Else
        Print #2, sLine
    End If
Loop
Close #1
Close #2

End Sub