【问题标题】:EXCEL VBA Replace last line cr+lf with lfEXCEL VBA 用 lf 替换最后一行 cr+lf
【发布时间】:2016-05-09 22:37:21
【问题描述】:

我有一个 Excel 文件的用户输入,我需要输出到 txt。 它被称为 csv,但分隔符不是“;”但是“|”所以我需要自己创建文件。

我最终创建了文件,但是我需要让每一行都以换行结束,它可以完成这项工作,但是在创建的文件的末尾有一个空行,带有 回车和换行 .

我怎样才能停止这个或用crlf删除最后一行??

这里的功能不是我的设计,我只是废弃了我在其他地方找到的功能。

现在我用这个:

Sub CreateAfile()

rok = Format(Date, "yyyy")
Mesic = Format(Date, "mm")
dnes = Format(Date, "dd")
cesta = "\\somepath\"
plnacesta = cesta & "Data_" & rok & Mesic & dnes & "_0001" & ".csv"
Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim pth As String
pth = ThisWorkbook.Path
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Dim a As Object
If myFileExists(plnacesta) Then
MsgBox "Existuje!"
Exit Sub
Else
End If
Set a = fs.CreateTextFile(plnacesta, True)
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Výsledek")

Dim rng As Range
Set rng = sh.UsedRange
Dim sRange As String
sRange = GetTextFromRangeText(rng)
Call a.WriteLine(sRange)
'Call a.WriteLine(sRange)
a.Close

End Sub

Function myFileExists(ByVal strPath As String) As Boolean
'Function returns true if file exists, false otherwise
If Dir(strPath) > "" Then
    myFileExists = True
Else
    myFileExists = False
End If
End Function

Function GetTextFromRangeText(ByVal poRange As Range) As String
Dim vRange As Variant
Dim sRet As String
Dim i As Integer
Dim j As Integer

If Not poRange Is Nothing Then

    vRange = poRange

    For i = LBound(vRange) To UBound(vRange)
        For j = LBound(vRange, 2) To UBound(vRange, 2)
            sRet = sRet & vRange(i, j)
        Next j
        sRet = sRet & vbLf
    Next i
End If

GetTextFromRangeText = sRet
End Function

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    我建议添加一个 if 条件

    For i = LBound(vRange) To UBound(vRange)
        For j = LBound(vRange, 2) To UBound(vRange, 2)
            sRet = sRet & vRange(i, j)
        Next j
        If(i<> UBound(vRange)) Then
           sRet = sRet & vbNewLine
        End If
    Next i
    

    【讨论】:

    • 用 cr+lf 删除最后一个空行。然而,最后一行现在以 cr+lf 而不是 lf 结尾。
    【解决方案2】:

    解决了它而不是

    Call a.WriteLine(sRange)
    

    应该是

    Call a.Write(sRange)
    

    由于write不加换行符

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 2016-03-28
      • 2011-06-03
      • 2012-07-05
      • 1970-01-01
      • 2010-12-04
      相关资源
      最近更新 更多