vba 如何获取打开的工作簿的文件扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27341904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:25:37  来源:igfitidea点击:

How to get the file extension of the open workbook

excelvba

提问by Terry

How to determine if the open workbook is a template (.xltm) or not. Basically, I have a template. If the user opens the template as (right-click >open) as .xltm file and tries to run a macro, I should prevent a macro from being executed. If the user double-clicks the template, it opens as .xlsm, in that case I have no issue.

如何确定打开的工作簿是否为模板 (.xltm)。基本上,我有一个模板。如果用户将模板作为(右键单击>打开)作为 .xltm 文件打开并尝试运行宏,我应该阻止执行宏。如果用户双击模板,它会以 .xlsm 格式打开,在这种情况下我没有问题。

Can someone please help me figure this out? Thanks in advance.

有人可以帮我解决这个问题吗?提前致谢。

Regards,

问候,

回答by singhm0077

you can use below example to get extension of file

您可以使用下面的示例来获取文件的扩展名

Sub extd()

Dim extFind As String
Dim sFile As String

        Const FilePath As String = "C:\Users\aa\Desktop\devces.docx"


        sFile = Dir(FilePath & filename & "*")

        extFind = Right$(sFile, Len(sFile) - InStrRev(sFile, "."))

        MsgBox extFind
End Sub

回答by Ameb

I was looking for the same. Since ActiveWorkbook.Namedepends on Windows property Hide extensions for known file types(If u have them hidden .Namewont return the extension), u can use Workbook.FileFormat. Returns an integer value, based on XlFileFormat enumeration. So, to check:

我正在寻找相同的。由于ActiveWorkbook.Name取决于 Windows 属性Hide extensions for known file types(如果你隐藏它们.Name不会返回扩展名),你可以使用Workbook.FileFormat. 返回一个整数值,基于XlFileFormat enumeration。所以,要检查:

Option Explicit
Sub sample()
    Debug.Print ActiveWorkbook.FileFormat
    Select Case ActiveWorkbook.FileFormat
        Case xlOpenXMLWorkbookMacroEnabled '52 xlsm
            Debug.Print "Its a workbook with macros enabled"
        Case xlOpenXMLTemplateMacroEnabled '53 xltm
            Debug.Print "Its a template with macros enabled"
        Case xlWorkbookDefault '51 xlsx
            Debug.Print "Its a workbook without macros"
    End Select
End Sub

Debug.PrintOutputs to inmediate window, u can open it with Ctrl+Gor in the view menu of the VB Editor.

Debug.Print输出到中间窗口,您可以使用Ctrl+GVB 编辑器的视图菜单或在其中打开它。

回答by Jeremy Morren

Use the Code below:

使用以下代码:

'e.g. Active Workbook name = text.xlsx
Dim wk AS Workbook: Set wk = ActiveWorkbook
Dim fileExtension As String
fileExtension = Right(wk.FullName, Len(wk.FullName) - InStrRev(wk.FullName, "."))
'File Extension is now "xlsx" (without the .)

fileExtension will now contain the workbook type, which can be used as you desire.

fileExtension 现在将包含工作簿类型,可以根据需要使用。