如何修改Excel宏,使保存文件名含昨日日期及DSP工作表B8单元格内容
修改Excel宏以在文件名中包含指定单元格内容
直接在原代码的文件名拼接部分插入Sheets("DSP").Range("B8").Value,就能把DSP工作表B8单元格的文本加入文件名,修改后的完整代码如下:
ActiveWorkbook.SaveAs Filename:= _ "\\mypath\\" & _ "Azal PHR " & Sheets("DSP").Range("B8").Value & " " & Format(Date - 1, "mm-dd-yyyy")
注意事项:
- 如果B8单元格的内容包含Windows文件名禁止的字符(比如
\ / : * ? " < > |),保存会失败。可以提前清理这些字符,示例代码如下:
' 先清理B8内容中的非法字符 Dim cleanCellText As String cleanCellText = Sheets("DSP").Range("B8").Value cleanCellText = Replace(cleanCellText, "\", "") cleanCellText = Replace(cleanCellText, "/", "") cleanCellText = Replace(cleanCellText, ":", "") cleanCellText = Replace(cleanCellText, "*", "") cleanCellText = Replace(cleanCellText, "?", "") cleanCellText = Replace(cleanCellText, """", "") cleanCellText = Replace(cleanCellText, "<", "") cleanCellText = Replace(cleanCellText, ">", "") cleanCellText = Replace(cleanCellText, "|", "") ' 用清理后的文本保存文件 ActiveWorkbook.SaveAs Filename:= _ "\\mypath\\" & _ "Azal PHR " & cleanCellText & " " & Format(Date - 1, "mm-dd-yyyy")
内容的提问来源于stack exchange,提问作者hussam
相关产品推荐
相关产品推荐

