依據儲存格(如 A1「客戶名稱」)內容自動命名檔案(如「客戶名稱.xlsx」),避免手動另存新檔輸入檔名。
Sub SaveAsCellValue()
Dim savePath As String
Dim fileName As String
' 取得儲存路徑(可改為 InputBox 或固定路徑)
savePath = "D:\Reports\" ' 確保資料夾存在
' 取得作用中儲存格值作為檔名
fileName = ActiveCell.Value
If fileName = "" Then
MsgBox "請先選取含檔名的儲存格!", vbExclamation
Exit Sub
End If
' 移除檔名非法字元
Dim illegalChars As Variant, ch As Variant
illegalChars = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
For Each ch In illegalChars
fileName = Replace(fileName, ch, "_")
Next ch
' 另存新檔
On Error Resume Next
ActiveWorkbook.SaveAs Filename:=savePath & fileName & ".xlsx", FileFormat:=xlOpenXMLWorkbook
If Err.Number <> 0 Then
MsgBox "儲存失敗:" & Err.Description, vbCritical
Else
MsgBox "已儲存為:" & savePath & fileName & ".xlsx", vbInformation
End If
On Error GoTo 0
End Sub
\ / : * ? " < > |`,程式碼已自動替換為底線。fileName & Format(Now, "yyyymmdd_hhnnss")。