excel 需要使用宏(VBA)删除前两行创建的额外逗号

w46czmvw  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(164)

需要您的帮助,以删除额外的尾随逗号这是越来越当我创建一个CSV文件使用宏生成

下面是我用来创建CSV文件,我尝试了各种选项,但它不工作,请帮助

Sub NEWMACRO ()

Dim complete_rec As String

mylogfile = FreeFile()

Dim rng As Range
Dim lLastRow As Integer
Dim lLastCol As Integer
    
Open "C:\File\ Range("A2").Value & ".csv" For Output Access Write As mylogfile

 Set rng = Range("A1").SpecialCells(xlCellTypeLastCell)
 lLastRow = rng.Row
 lLastCol = rng.Column

For irow = 1 To lLastRow
       For icol = 1 To lLastCol
        If icol = 1 Then
            complete_rec = Application.Cells(irow, icol).Value
        Else
            complete_rec = complete_rec & "," & Application.Cells(irow, icol).Value
        End If
    Next icol
    
    complete_rec = complete_rec + " "
    Print #mylogfile, complete_rec
Next irow
Close mylogfile

End Sub
jyztefdp

jyztefdp1#

如果您不希望这些尾随逗号,那么您需要读取每一行,直到该行的最后一个值,而不是假设所有行都有相同的结束点。
这里有一个你可以使用的方法:

Sub NEWMACRO()

    Dim sLine As String, sep As String
    Dim rng As Range, ws As Worksheet
    Dim lLastRow As Long, arr, mylogfile, rw As Long, col As Long
    
    Set ws = ActiveSheet 'for example
    'last occupied row on the sheet
    lLastRow = ws.Cells.Find(what:="*", After:=ws.Range("A1"), _
                LookAt:=xlPart, LookIn:=xlFormulas, _
                SearchOrder:=xlByRows, SearchDirection:=xlPrevious, _
                        MatchCase:=False).Row
        
    mylogfile = FreeFile()
    Open "C:\Temp\Test2.csv" For Output Access Write As mylogfile
    
    'loop over all rows
    For rw = 1 To lLastRow
        sLine = "": sep = ""
        'read only the occupied part of the row
        arr = asArray(ws.Range(ws.Cells(rw, 1), _
                       ws.Cells(rw, ws.Columns.Count).End(xlToLeft)))
        For col = LBound(arr, 2) To UBound(arr, 2)
            sLine = sLine & sep & arr(1, col)
            sep = ","
        Next col
        Print #mylogfile, sLine
    Next rw
    
    Close mylogfile
End Sub

'read a range into a 2D array, allowing for the single-cell case
Function asArray(rng As Range)
    Dim arr()
    If rng.Cells.CountLarge = 1 Then
        ReDim arr(1 To 1, 1 To 1)
        arr(1, 1) = rng.Value
        asArray = arr
    Else
        asArray = rng.Value
    End If
End Function

相关问题