我对微软VBA完全陌生,而且我在修复Excel宏时遇到了麻烦。
这个宏的目的是,当按下按钮时,它会自动将活动工作表保存在文件中,但它不起作用,我不知道原因。
对我来说似乎是正确的。
Sub Save()
'
' Save Macro
'
Sheets("My_sheet").Select
ChDir "C:\my_file"
ActiveWorkbook.SaveAs Filename:=Range("B6"), FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, _
CreateBackup:=False
Sheets("My_sheet").Select
'
End Sub
答案 0 :(得分:0)
只要工作表名称设置为“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