确定 Excel 模板路径
Determine Excel Template Path
我有一个 Excel 2007 模板,我想让其他人能够使用它。作为代码的一部分,我需要知道模板最初所在的位置,因为根据用户放置它的位置,位置可能会有所不同。从模板创建新工作簿时,它在 ActiveWorkBook.Path 值中没有值,直到将其保存在某处后才会填充。
有什么方法可以确定创建工作簿的模板路径吗?
如果模板有一个唯一的名称,并且您知道它存储在哪个驱动器上,您可以使用类似的名称:
Function GetTemplatePath(drive As String, templateName As String) As String
Dim cmd As String, result As String
cmd = "CMD /C DIR """ & drive & ":\*" & templateName & """ /S /B /A:-D"
On Error Resume Next
result = Split(CreateObject("WScript.Shell").Exec(cmd).StdOut.ReadAll, vbCrLf)(0)
On Error GoTo 0
If InStr(result, "\") Then
GetTemplatePath = Left(result, InStrRev(result, "\"))
Else
GetTemplatePath = vbNullString
End If
End Function
您可以这样使用它:
Dim filePath As String
filePath = GetTemplatePath("C", "MyTemplate.xltx")
Debug.Print filePath
我有一个 Excel 2007 模板,我想让其他人能够使用它。作为代码的一部分,我需要知道模板最初所在的位置,因为根据用户放置它的位置,位置可能会有所不同。从模板创建新工作簿时,它在 ActiveWorkBook.Path 值中没有值,直到将其保存在某处后才会填充。
有什么方法可以确定创建工作簿的模板路径吗?
如果模板有一个唯一的名称,并且您知道它存储在哪个驱动器上,您可以使用类似的名称:
Function GetTemplatePath(drive As String, templateName As String) As String
Dim cmd As String, result As String
cmd = "CMD /C DIR """ & drive & ":\*" & templateName & """ /S /B /A:-D"
On Error Resume Next
result = Split(CreateObject("WScript.Shell").Exec(cmd).StdOut.ReadAll, vbCrLf)(0)
On Error GoTo 0
If InStr(result, "\") Then
GetTemplatePath = Left(result, InStrRev(result, "\"))
Else
GetTemplatePath = vbNullString
End If
End Function
您可以这样使用它:
Dim filePath As String
filePath = GetTemplatePath("C", "MyTemplate.xltx")
Debug.Print filePath