拒绝保存好像单元格没有值

时间:2015-11-24 17:49:17

标签: excel excel-vba excel-2010 vba

我有一个脚本,用于根据两个单元格/命名范围(FailReportSN和FailReportDD)的内容保存Excel模板。我的问题是,在运行下面的save as脚本之前,最终用户并不总是记得在这两个单元格中输入值。我需要做的是修改我当前的脚本,只有在两个单元格中都有值时才能保存。

Sub saveAsFATPMM() 
Dim PathMac As String, Path As String, FolderPath As String

 If Application.PathSeparator = ":" Then 
  FolderPath = "Volumes:Server:Groups:METI:Quality Control:METIman:" 
  PathMac = FolderPath & Sheets("Failure Report").Range("FailReportSN").Text & _ 
      " - FATP - " & Sheets("Failure Report").Range("FailReportDD").Text & ".xlsm" 
   'Format(Date, "mm-dd-yy") 
  ThisWorkbook.SaveAs Filename:=PathMac, FileFormat:=53, CreateBackup:=True 
 Else 
  FolderPath = "\\server\server\Groups\METI\Quality Control\METIman\" 
  Path = FolderPath & Sheets("Failure Report").Range("FailReportSN").Text & _ 
  " - FATP - " & Sheets("Failure Report").Range("FailReportDD").Text & ".xlsm" 
  'Format(Date, "mm-dd-yy") 
  ThisWorkbook.SaveAs Filename:=Path, FileFormat:=52, CreateBackup:=True 
 End If

MsgBox "Your file has been saved. Thank you." 
End Sub

1 个答案:

答案 0 :(得分:1)

使用条件If首先检查这些值。在下面的代码中,我检查以确保该范围的Len不为0(或者在这种情况下为False,因为0在此等于False)。我还重构了一点,以摆脱基本上重复的代码。

Sub saveAsFATPMM()

With Sheets("Failure Report")

    If Len(.Range("FailReportSN")) And Len(.Range("FailReportDD")) Then

        Dim PathMac As String, Path As String, FolderPath As String, fFormat as Long

        If Application.PathSeparator = ":" Then

            FolderPath = "Volumes:Server:Groups:METI:Quality Control:METIman:"
            fFormat = 53

        Else

            FolderPath = "\\server\server\Groups\METI\Quality Control\METIman\"
            fFormat = 52     

        End If

        Path = FolderPath & .Range("FailReportSN").Text & _
            " - FATP - " & .Range("FailReportDD").Text & ".xlsm"

        ThisWorkbook.SaveAs Filename:=Path, FileFormat:=fFormat, CreateBackup:=True

        MsgBox "Your file has been saved. Thank you."

    Else

        MsgBox "File not saved! Enter Fail Report Values and Try Again!"

    End If

End With

End Sub