停止使用目标文件名更改源文件名

Stop changing the source file name with destination file name

我觉得这很酷 VBA,它确实做到了它所说的, 但正如我观察到的那样,它一直在用目标文件名

更改源文件名

任何人都可以提供另一行代码来停止更改源文件 这个宏实际上做的是, 它使用用户提供的名称在目标目录中创建一个文本文件

但同时它也在重命名我的实际文件,这出乎我的意料,

感谢这里所有的善良和天才,祝你周末愉快。干杯!!

Sub CreateTextFile()
Dim myFolder As String
'By Joe Was.
'Save Range as Text File.

ActiveSheet.Activate
'Ask user to select range for text file.
Set myRange = Application.InputBox(prompt:="Please select a range!", _
Title:="Text File Range!", Type:=8)
myRange.Select
Selection.Copy
'This temporarily adds a sheet named "Test."
Sheets.Add.Name = "Test"
Sheets("Test").Select
ActiveSheet.Paste
'Ask user for folder to save text file to.
myFolder = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
'Save selected data as text file in users selected folder.
'ActiveWorkbook.SaveAs Filename:=myFolder, FileFormat:=xlText, CreateBackup:=False
ActiveWorkbook.SaveAs Filename:=myFolder, FileFormat:=xlTextPrinter, CreateBackup:=False
'Remove temporary sheet.
Application.ScreenUpdating = False
Application.DisplayAlerts = False
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
'Indicate save action.
MsgBox "Text File: " & myFolder & "Saved!"
'Go to top of sheet.
Range("A1").Select
End Sub

ActiveWorkbook.SaveAs 文件名:=myFolder,文件格式:=xlTextPrinter,CreateBackup:=False 这部分是有问题的。 如果你想保留原来的名字,你应该将数据复制到一个新的工作簿中,保存后可以关闭。

尝试这样的事情:

Sub CreateTextFile()
Dim myFolder As String
'By Joe Was.
'Save Range as Text File.
'Edited by Lonolian
Dim AWB As Workbook <-- Added
ActiveSheet.Activate
'Ask user to select range for text file.
Set myRange = Application.InputBox(prompt:="Please select a range!", _
Title:="Text File Range!", Type:=8)
myRange.Select
Selection.Copy
'This temporarily adds a sheet named "Test."
Sheets.Add.Name = "Test"
Sheets("Test").Select
ActiveSheet.Paste
Application.CutCopyMode = False '<---------Edited
Sheets("Test").Move             '<---------Edited
Set AWB = ActiveWorkbook
'Ask user for folder to save text file to.
myFolder = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
'Save selected data as text file in users selected folder.
'ActiveWorkbook.SaveAs Filename:=myFolder, FileFormat:=xlText, CreateBackup:=False
AWB.SaveAs Filename:=myFolder, FileFormat:=xlTextPrinter, CreateBackup:=False
'Remove temporary sheet.
AWB.Close True <--- Editied
'Indicate save action.
MsgBox "Text File: " & myFolder & "Saved!"
'Go to top of sheet.
Range("A1").Select
End Sub