Saving .txt as .csv cancels all changes made by macro in the file. How to prevent it?

前端 未结 1 1870
广开言路
广开言路 2021-01-29 07:32

The issue continues this topic and is associated with my earlier post. The code should deal with .csv files changing cells\' values and interior color. It does its job, but afte

相关标签:
1条回答
  • 2021-01-29 07:54

    What looked as a simple opening semicolon delimited text /cvs file in your earlier post is now looks complicated. Even overlooking other issues, in my trial, I find while saving txt/csv files from excel it may introduce some double quote in the saved file (depending on position of comma, spaces and semicolon in a line). May refer links (Saving a Excel File into .txt format without quotes) and link and link2

    As what I understand, your requirement is simple to truncate 5th column of the semicolon delimited file with csv extension and save it back, the simple approach of may solve your the problem. However, I still not satisfied with the workaround approach and invite more simple and straight approach to solve the problem (consisting txt file with comma, spaces and semicolons, while semicolon is to be treated as delimiter)

    Try

    Sub test2()
    Dim Fname As String, Path As String, Txt As String, Txt2 As String
    Dim INum As Integer, ONum As Integer, TrucTo As Integer, ColNo As Long
    Dim Cols As Variant
    
    ' Modify the variables to your requirement
    Path = "C:\Users\user\Desktop\"
    Fname = "Somefile.csv"     ' Target file name
    Fname2 = "Somefile2.csv"   ' Temp file name
    TrucTo = 10                ' truncated to chars
    ColNo = 4                   '  column to be truncated -1
    
    If Dir(Path & Fname2) <> "" Then Kill Path & Fname2
    
    
    INum = FreeFile
    Open Path & Fname For Input As #INum
    ONum = FreeFile
    Open Path & Fname2 For Output As #ONum
    
    Do Until EOF(1)
        Line Input #1, Txt
        Cols = Split(Txt, ";")
            If UBound(Cols) >= ColNo Then
                If Len(Cols(ColNo)) >= truncto Then
                Cols(ColNo) = Left(Cols(ColNo), TrucTo)
                End If
            End If
        Txt2 = Join(Cols, ";")
        Print #ONum, Txt2
    Loop
    Close #ONum
    Close #INum
    
    
    Kill Path & Fname
    Name Path & Fname2 As Path & Fname
    
    
    End Sub
    

    This is the result input & Output

    0 讨论(0)
提交回复
热议问题