似乎很好,只要工作,因爲工作表名稱設置爲 「My_Sheet」 文件夾中和文件名是正確的。 您可以試試這個來檢查它們在保存前是否正常:
Sub SaveMe()
Dim filename As String
'check if directory exist
If Dir("C:\my_file", vbDirectory) = "" Then
'if not ask if it should be created and continued
rspCreate = MsgBox("Directory doesn't exist, do you wish to create it and continue?", vbYesNo)
If rspCreate = vbYes Then
'create dir and carry on
MkDir "C:\my_file"
ElseIf rspCreate = vbNo Then
'no selected, stop execution
Exit Sub
End If
End If
filename = Range("B6")
Sheets("My_sheet").Select
ChDir "C:\my_file"
'check if file name is valid
If FileNameValid(filename) Then
ActiveWorkbook.SaveAs filename:=Range("B6"), FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, _
CreateBackup:=False
Else
MsgBox "Invalid file name, file not saved"
End If
Sheets("My_sheet").Select
End Sub
'check if vali file name is used in cell
Function FileNameValid(sFileName As String) As Boolean
Dim notAllowed As Variant
Dim i As Long
Dim result As Boolean
'list of forbidden characters
notAllowed = Array("/", "\", ":", "*", "?", "< ", ">", "|", """")
'Initial result = OK
result = True
For i = LBound(notAllowed) To UBound(notAllowed)
If InStr(1, sFileName, notAllowed(i)) > 0 Then
'forbidden character used
result = False
Exit Function
End If
Next i
FileNameValid = result
End Function
來源
2016-09-22 09:00:19
Pav
什麼不起作用?你有錯誤嗎?範圍(「B6」)中有什麼? – Comintern
我收到一個錯誤,其中突出顯示「表格(」My_sheet「)。選擇」這個宏的一部分,我不能保存工作表。 '範圍(「B6」)'這是一個寫一個名字的單元格。這個名稱需要是保存文件的名稱。 – Rods2292
我假設你有一張名爲「My_sheet」的工作表?什麼是錯誤? – Comintern