我有一个重命名文件的 VBA 宏。我有这个文件存在的完整路径,但我想独立于它的位置重命名这个文件。
Private Sub Workbook_Open()
Dim sFileName As String, sNewFileName As String
sFileName = "C:\Users\me\Desktop\text.txt"
sNewFileName = "C:\Users\me\Desktop\test1.txt"
If Dir(sFileName, 16) = "" Then MsgBox "File not found", vbCritical, "Error": Exit Sub
Name sFileName As sNewFileName 'rename file
MsgBox "file has been renamed"
End Sub
我的意思是,如果您使用此 Excel 文件和text.txt
文件提取存档并启动它,test.txt
它将独立于其位置找到并重命名它。
您正在寻找ThisWorkbook.Path
它为您提供正在使用的工作簿的路径。因此,如果您的 txt 文件在同一目录中,您可以使用以下内容:
sFileName = ThisWorkbook.Path & "\text.txt"
sNewFileName = ThisWorkbook.Path & "\test1.txt"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句