vba - 确保文件名以特定字符串开头

标签 vba excel

我一直在玩这个代码。理想情况下,我可以强制用户将文件名保存为以 Lowpar 开头,尽管我可以做到这一点,但代码无法有效工作。例如,我想调用文件 Lowpar2016 但使用此代码将无法正常工作。

Private Sub Workbook_BeforeSave _
(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim NamePath As String
Dim strName As String
Dim lFind As Long

   If SaveAsUI = True Then' unless this is set to <> true, it does not work
      Cancel = True
      With Application
          .EnableEvents = False
          NamePath = .GetSaveAsFilename
          strName = Mid(NamePath, InStrRev(NamePath, "\", -1, vbTextCompare) + 1, 256)

          If NamePath = "False" Then' this is part of the code that confuses me
              .EnableEvents = True
              Exit Sub
          ElseIf left(strName,6) <> "Lowpar" Then
              MsgBox "You cannot save as another name"
              .EnableEvents = True
              Exit Sub
          Else
              Me.SaveAs NamePath
              .EnableEvents = True
          End If
      End With
   End If
End Sub

最佳答案

以下重构代码将强制名称以 LowPar 开头如果还没有:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

Dim NamePath As String
Dim strName As String
Dim lFind As Long

   If SaveAsUI = True Then ' unless this is set to <> true, it does not work

    Cancel = True
    With Application

        .EnableEvents = False
        NamePath = .GetSaveAsFilename
        strName = Mid(NamePath, InStrRev(NamePath, "\", -1, vbTextCompare) + 1, 256)

        If NamePath = "False" Then ' this is part of the code that confuses me
            .EnableEvents = True
            Exit Sub
        ElseIf Left(strName, 6) <> "Lowpar" Then
            NamePath = "LowPar_" & NamePath
        End If

        Me.SaveAs NamePath
        .EnableEvents = True

    End With

   End If

End Sub

关于vba - 确保文件名以特定字符串开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38384252/

相关文章:

excel - 复制图像 - Excel VBA

vba - Excel:在 VBA 中选择单个单元格与整列

vba - 使用在类中创建的函数 - VBA

vba - 从另一个子调用类型变量

forms - ACCESS 2010 系统资源超标

excel - ADODB.Recordset 上的“类型不匹配”错误

excel - 使用 Excel,尝试从外部 HTA 中查找真正使用过的范围

excel - 超出嵌套 IF 和公式的可接受范围不起作用

excel - 循环遍历文件夹下的所有子文件夹和文件,并将最后修改日期信息写入Excel电子表格

excel - 使用VBA删除具有空白系列名称的图例条目