を参照してください。 保存する前に確認することができます:
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
何が問題なのですか?間違いはありますか? 'Range(" B6 ")とは何ですか? – Comintern
"シート(" My_sheet ")を強調表示するエラーが表示されます。このマクロの一部を選択して、ワークシートを保存できません。 'Range(" B6 ")'は名前が書かれたセルです。この名前は、保存されたファイルの名前である必要があります。 – Rods2292
「My_sheet」という名前のシートがあるとしますか?エラーは何ですか? – Comintern