vba 如何在Excel中更改文档的名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11370300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 16:47:13  来源:igfitidea点击:

How to change the name of the document in Excel?

excelvbaexcel-vbaexcel-2010

提问by AngryHacker

I have a Macro Enabled Template called TIP-PBI.xltm. When I create a document based on this template, Excel automatically names it TIP-PBI1. However, I want to give it a custom name.

我有一个名为 TIP-PBI.xltm 的启用宏的模板。当我基于此模板创建文档时,Excel 会自动将其命名为 TIP-PBI1。但是,我想给它一个自定义名称。

I figured I could do that by modifying the .Title property of the Workbook. To that end, on startup the Workbook_Open event kicks off, and the following is executed:

我想我可以通过修改工作簿的 .Title 属性来做到这一点。为此,在启动时 Workbook_Open 事件开始,并执行以下操作:

Private Sub Workbook_Open()
    Dim strPBI As String
    strPBI = InputBox$("Enter PBI", "Enter PBI")

    ThisWorkbook.Title = "TIP-PBI-" & strPBI
End Sub

However, this does nothing.

然而,这没有任何作用。

How can I change the Title of the document on startup?

如何在启动时更改文档的标题?

回答by T I

the only way to change the workbook name is to save it (ref) so you could do something like

更改工作簿名称的唯一方法是保存它(ref),以便您可以执行以下操作

ThisWorkbook.SaveAs ThisWorkbook.Path & "" & FileName & ".xls"

if you only want to suggest a name then you could use GetSaveAsFilenameor

如果您只想建议一个名称,那么您可以使用GetSaveAsFilename

Application.FileDialog(msoFileDialogSaveAs).InitialFileName = ThisWorkbook.Path & "" & FileName & ".xls"

回答by Nej Sanerkin

If the new workbook is created from a template then it takes the template name. Hence in instances where I wish to set the name of the new work book I copy a dummy template to the required name and then open the new workbook based upon the renamed template.

如果新工作簿是从模板创建的,则它采用模板名称。因此,在我希望设置新工作簿名称的情况下,我将一个虚拟模板复制到所需的名称,然后根据重命名的模板打开新工作簿。

 strFile = "C:\Temp\" & strnewname & ".xltx "

 FileCopy "C:\Temp\Dummy.xltx", strFile

 'Open template to new workbook

 Workbooks.Open Filename:=strFile

 Kill strFile  'delete renamed template