Visual Basic Excel函数将文件命名为单元格内容

我想在Visual Basic中编写一个函数来创build基于特定单元格中的值的电子表格的文件名。

到目前为止,我一直在使用这个代码:

Public Sub SaveAsA1() ThisFile = "RWO_" + Format(Now(), "yyyymmdd") + "_" + Format(Now(), "hhmm") + "_" + Range("D4").Value + "_" + Range("F5").Value + "_" + Range("D8").Value ActiveWorkbook.SaveAs Filename:=ThisFile End Sub 

这段代码是我第一次保存文件,但是每当我重新保存文件时,它都不会根据单元格中的新值更新文件名。

有谁知道我怎么可以去写一个函数来做到这一点?

您可以尝试添加BeforeSave event代码。 它会正常保存文件,但会按照您的预期每次按SaveAs button更改名称。

此代码应位于ThisWorkbook模块(工作簿模块)中。

 Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) If SaveAsUI = True Then Application.EnableEvents = False Dim ThisFile As String ThisFile = "RWO_" + Format(Now(), "yyyymmdd") + "_" + Format(Now(), "hhmmss") + "_" + Range("D4").Value + "_" + Range("F5").Value + "_" + Range("D8").Value & ".xlsm" ActiveWorkbook.SaveAs Filename:=ThisFile, FileFormat:=XlFileFormat.xlOpenXMLWorkbookMacroEnabled Application.EnableEvents = True Cancel = True End If End Sub 

请注意,我已经通过添加ss到时间和.xlsm扩展名来更改ThisFile 。 另外我已经将FileFormat parameter添加到.SaveAs method