VBA - Excel - Save As and delete original workbook

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 04:23:47

问题


From a Personal.xlsb file, I want VBA to save the current active workbook as a user-definable name in the same directory and delete the original workbook.

Below is my code. It has two problems. One, it saves the workbook in My Documents folder for some reason. The active workbook is not in My Documents. It's in a folder in a completely different drive. Two, it throws a "File not found" error.

Sub RenameFile()
Dim thisWb As Workbook
Set thisWb = ActiveWorkbook
MyOldName = ActiveWorkbook.Name
MyNewName = InputBox("What do you want to rename the file as?", "Rename", ActiveWorkbook.Name)

ActiveWorkbook.SaveAs Filename:=thisWb.Path & MyNewName
Kill MyOldName
End Sub

回答1:


You need to include a \ after path and before filename.

Sub RenameFile()
Dim thisWb As Workbook
Set thisWb = ActiveWorkbook
MyOldName = ActiveWorkbook.FullName
MyNewName = InputBox("What do you want to rename the file as?", "Rename", ActiveWorkbook.Name)

ActiveWorkbook.SaveAs Filename:=thisWb.Path & "\" & MyNewName
Kill MyOldName
End Sub

Edit: Updated answer to include fix from comment.




回答2:


So I have some code that I use to auto save files (to a directory specified in the code) and then deletes a particular file type out of said folder. (I use it to save a .xlsx and delete .csv)

'Saves file to specified location
    ActiveWorkbook.SaveAs filename:="C:\Desktop\Testing\Testing File " _
    & Format(Now() - 1, "DD.MM.YY") & ".xlsx" _
    , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

    On Error Resume Next
    Kill "C:\Desktop\Testing*.csv*"
    On Error GoTo 0

This is the code that I used that is within a longer VBA module, but you could incorporate this into existing VBA code

Take note that that currently saves the file as Testing with the day before the current system date in the name, such as "Testing 30.10.16"



来源:https://stackoverflow.com/questions/40344016/vba-excel-save-as-and-delete-original-workbook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!