Excel VBA – 保存为.xlsx扩展名

这是我重命名文件的代码。 它做一个SaveAs然后删除原来的。 这需要在不同types的工作簿上运行:一些扩展名为.xls,另一些扩展名为.xlsx。 如果它有一个.xls扩展名,我需要强制它有一个.xlsx扩展名。

我怎样才能做到这一点,而不是在popup的时候在InputBox的空白处input“x”?

或者也许这个问题有不同的解决scheme? 我的目标是强制InputBox显示一个.xlsx扩展名的当前文件名,不pipe当前是什么。

Sub RenameFile() Dim myValue As Variant Dim thisWb As Workbook Set thisWb = ActiveWorkbook MyOldName2 = ActiveWorkbook.Name MyOldName = ActiveWorkbook.FullName MyNewName = InputBox("Do you want to rename this file?", "File Name", _ ActiveWorkbook.Name) If MyNewName = vbNullString Then Exit Sub If MyOldName2 = MyNewName Then Exit Sub Application.DisplayAlerts = False ActiveWorkbook.SaveAs Filename:=thisWb.Path & "\" & MyNewName, _ FileFormat:=51 Kill MyOldName End Sub 

如果新的扩展名总是为.xlsx ,为什么不把扩展名完全留在input框之外:

 Dim fso As New Scripting.FileSystemObject MyNewName = InputBox("Do you want to rename this file?", "File Name", _ fso.GetBaseName(ActiveWorkbook.Name)) & ".xlsx" 

请注意,这需要参考Microsoft脚本运行时。

你想在MsgBox的位置展示扩展吗? 以下代码将强制将扩展更改为您指定的任何types。 只需添加您想要处理的其他转换的代码。 如果要在Msgbox中显示新扩展名,请复制我添加的代码并将其放在MsgBox之前。 如果你想'保证'新的扩展名,你需要保留在Msgbox之后的代码,以防用户推翻你的build议。

 Sub RenameFile() Dim myValue As Variant Dim thisWb As Workbook Dim iOld As Integer Dim iNew As Integer Dim iType As Integer Set thisWb = ActiveWorkbook Dim MyOldName2, MyOldName, MyNewName As String MyOldName2 = ActiveWorkbook.Name MyOldName = ActiveWorkbook.FullName MyNewName = InputBox("Do you want to rename this file?", "File Name", _ ActiveWorkbook.Name) If MyNewName = vbNullString Then Exit Sub If MyOldName2 = MyNewName Then Exit Sub iOld = InStrRev(MyOldName, ".") iNew = InStrRev(MyNewName, ".") If LCase(Mid(MyOldName, iOld)) = ".xls" Then MyNewName = Left(MyNewName, iNew - 1) & ".xlsx" iType = 51 ElseIf LCase(Mid(MyOldName, iOld + 1)) = ".YYYY" Then ' Add lines as needed for other types MyNewName = Left(MyNewName, iNew - 1) & ".ZZZZ" ' Must change type to match desired output type iType = 9999 Else MsgBox "Add code to handle extension name of '" & LCase(Mid(MyOldName, iOld)) & "'", vbOKOnly, "Add Code" Exit Sub End If Application.DisplayAlerts = False ActiveWorkbook.SaveAs Filename:=thisWb.Path & "\" & MyNewName, FileFormat:=iType Kill MyOldName End Sub