【问题标题】:How can I adapt my VBA code to check to see if the file name is already taken?如何调整我的 VBA 代码以检查文件名是否已被使用?
【发布时间】:2020-12-12 22:35:39
【问题描述】:

如果可能,我想添加代码来检查“返回注释”中是否存在与 B1 具有相同文本值的文件(其中包含要成为的文件名)

Private Sub CommandButton1_Click()

Dim NameofWorkbook As String

NameofWorkbook = "RN" & Range("B1")

MyMsg = NameofWorkbook + " " & "saved to return note folder"

'Create and assign variables
Dim saveLocation As String
saveLocation = "S:\Office information\Returns\Return Notes\" + NameofWorkbook

'Save Active Sheet(s) as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
    Filename:=saveLocation

MsgBox MyMsg

End Sub

工作代码(感谢 Romulax):

Private Sub CommandButton1_Click()

Dim NameofWorkbook As String
Dim levSave As String

NameofWorkbook = "RN" & Trim(Range("B1"))

MyMsg = NameofWorkbook + " " & "saved to return note folder"

'Create and assign variables
Dim saveLocation As String

saveLocation = "S:\Office information\Returns\Return Notes\" & NameofWorkbook
lenSave = saveLocation & ".pdf"

If Len(Dir(lenSave)) = 0 Then
    MsgBox "File does not exist"
    'Do stuff

'Save Active Sheet(s) as PDF
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
     Filename:=saveLocation

MsgBox MyMsg

Else

MsgBox "Filename taken."

End If
End Sub

【问题讨论】:

    标签: excel vba pdf duplicates


    【解决方案1】:

    here
    在你的情况下:

    If Len(Dir(saveLocation)) = 0 Then
      MsgBox "File does not exist"
      'Do stuff
    Else
        MsgBox "File does exist"
        'Do stuff
    End If
    

    也替换这个:

    saveLocation = "S:\Office information\Returns\Return Notes\" + NameofWorkbook
    

    有了这个:

    saveLocation = "S:\Office information\Returns\Return Notes\" & NameofWorkbook
    

    要连接,您必须使用& 而不是+

    编辑:如果您要查找的文件是 excel 文件“.xlsm”,并且如果“.xlsm”不在Range("B1") 中,则必须将其包含在代码中。这样,您的保存位置是:

    saveLocation = "S:\Office information\Returns\Return Notes\" & NameofWorkbook & ".xlsm"
    

    用实际文件类型替换“.xlsm”

    【讨论】:

    • 也许可以试试NameofWorkbook = "RN" & Trim(Range("B1")) Trim 去掉了不需要的空格,除了单词之间的单个空格
    • 再次感谢Romulax,不幸的是仍然没有运气。我在原始帖子中给出了我的代码的当前版本
    • 另外你确定文件目录是以“S”开头的吗?如果它不是辅助驱动器,通常它以“C”开头。你能解释一下现在的代码是什么,它是显示一个 msgbox 还是只是在某个地方崩溃?还是什么都没有?
    • 是的,它绝对是“S”。我正在共享驱动器上的一个项目。我仍然没有成功。代码显示“文件不存在”并运行其余代码(即完成保存)
    • 请记住,如果不是,您必须在目录末尾包含“.xlsm”或“.xlsx”(或其他文件格式,具体取决于您要查找的文件)在Range("B1")。查看编辑的答案,让我更新
    猜你喜欢
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    相关资源
    最近更新 更多