gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:59:08 25 4
gpt4 key购买 nike

我一直在玩这个代码。理想情况下,我可以强制用户将文件名保存为以 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com