如何在此VBA代码中更改目录?VBA“ Excel到TXT或CSV”


0

我真的想更改此代码的目录,Application.ActiveWorkbook.Path但我不知道将其放置在哪里。

Public Sub CharacterSV()
    Const DELIMITER As String = "|"
    Dim myRecord As Range
    Dim myField As Range
    Dim nFileNum As Long
    Dim sOut As String

    nFileNum = FreeFile
    Open ActiveWorkbook.Name & ".txt" For Output As #nFileNum
    For Each myRecord In Range("A1:A" & _
                Range("A" & Rows.Count).End(xlUp).Row)
        With myRecord
            For Each myField In Range(.Cells, _
                    Cells(.Row, Columns.Count).End(xlToLeft))
                sOut = sOut & DELIMITER & myField.Text
            Next myField
            Print #nFileNum, Mid(sOut, 2)
            sOut = Empty
        End With
    Next myRecord
    Close #nFileNum
End Sub

我试图弄清楚它,真的很想学习VBA,但我无法使其正常工作。

提前致谢!

Answers:


0

将此添加到您的代码:
Dim fname as string fname = "c:\documents and settings\desktop\" Open fname & ActiveWorkbook.Name & ".txt" For Output As #nFileNum

将目录替换为您的目录,打开将在目录中打开新文件,请注意在fname中写入真实且正确的路径。


0

感谢您的启发。

我只是通过了另一个使它更简单的代码。因为我只想将文件添加到我正在使用的目录中,但想使vba动态。

所以我用ActiveWorkbook.FullName代替了ActiveWorkbook.Name。我还在表中添加了名称" - " & ActiveSheet.Name &

这是最终代码(还添加了工作表名称):

Public Sub Worksheet_naar_TXT_Pipe_delimiter()
    Const DELIMITER As String = "|"
    Dim myRecord As Range
    Dim myField As Range
    Dim nFileNum As Long
    Dim sOut As String

    nFileNum = FreeFile
    Open ActiveWorkbook.FullName & " - " & ActiveSheet.Name & ".txt" For Output As #nFileNum
    For Each myRecord In Range("A1:A" & _
                Range("A" & Rows.Count).End(xlUp).Row)
        With myRecord
            For Each myField In Range(.Cells, _
                    Cells(.Row, Columns.Count).End(xlToLeft))
                sOut = sOut & DELIMITER & myField.Text
            Next myField
            Print #nFileNum, Mid(sOut, 2)
            sOut = Empty
        End With
    Next myRecord
    Close #nFileNum
End Sub

感谢您的回复,这使我想到了这个主意!


投票并标记帮助您的答案为“正确”是正确的,以感谢答谢者的帮助。
Raystafarian
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.