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

时间:2018-12-21 12:48:38

标签: excel vba robots.txt save-as

我发现了这个非常酷的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

1 个答案:

答案 0 :(得分:0)

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