用于将文件保存在特定位置的宏

时间:2018-07-23 07:31:08

标签: excel vba excel-vba

嗨,我有以下宏,它将每个工作表另存为.txt,文件名作为工作簿中工作表的名称,我想修改此宏,以便将每个工作表另存为sheetname.txt在特定位置而不是保存弹出对话框,每次选择文件位置。

Private Sub CommandButton1_Click()
'Updateby20150910
    Dim xRet As Long
    Dim xFileName As Variant
    On Error GoTo ErrHandler:
    xFileName = Application.GetSaveAsFilename(ActiveSheet.Name, "TXT File (*.txt), *.txt", , "VBA for Excel")
    If xFileName = False Then Exit Sub
    If Dir(xFileName) <> "" Then
        xRet = MsgBox("File '" & xFileName & "' exists.  Overwrite?", vbYesNo + vbExclamation, "VBA for Excel")
        If xRet <> vbYes Then
            Exit Sub
        Else
            Kill xFileName
        End If
    End If
    ActiveSheet.Copy
    ActiveWorkbook.SaveAs xFileName, xlUnicodeText
    If ActiveWorkbook.Name <> ThisWorkbook.Name Then
        ActiveWorkbook.Close False
    End If`enter code here
My_Exit:
    Exit Sub
ErrHandler:
    MsgBox Err.Description, , "error"
End Sub`enter code here

`

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

Private Sub CommandButton1_Click()    

    Dim ws As Worksheet
    Dim path As String

    path = "yourpath\"

    For Each ws In ThisWorkbook.Worksheets

         ws.Select
         If Dir(path & ws.Name) = "" Then
             ThisWorkbook.SaveAs Filename:=path & ws.Name, FileFormat:=-4158 'fileformat : txt
         Else
             Debug.Print ("File already exists!")
         End If

     Next ws

End Sub