我创建了一个简单的空excel文件,并在工作簿上编写了一个简单的宏:
Private Sub Workbook_NewSheet(ByVal Sh As Object)
MsgBox ThisWorkbook.Path
End Sub
打开文件并在excel文件中插入新工作表后,msgBox不显示任何内容。但保存文件后,MsgBox显示正确的地址。这是为什么?!如何在文件刚刚打开后获取文件地址?
答案 0 :(得分:1)
它是因为新创建的工作簿还没有路径!
一旦你保存它,它就会有一条真正的路径
您可以按如下方式更改您的子资料:
Private Sub Workbook_NewSheet(ByVal Sh As Object)
If ThisWorkbook.Path = "" Then '<--| if the workbook doesn't have path, yet
With Application.FileDialog(msoFileDialogSaveAs) '<--| have the user choose a path and a name
.Title = "Select Folder and name"
.InitialFileName = "C:\"
If .Show = 0 Then Exit Sub '<--| if the user canceled the dialog box then exit sub
ThisWorkbook.SaveAs .SelectedItems(1), xlOpenXMLWorkbookMacroEnabled '<--| otherwise save the workbook to the specified path as a macro enabled excel file
End With
End If
MsgBox ThisWorkbook.Path '<--| finally show the workbook path!
End Sub