【问题标题】:Get name and path of opened Workbook using VBA使用 VBA 获取打开的工作簿的名称和路径
【发布时间】:2018-03-17 19:26:10
【问题描述】:

我只是想问一下我如何获得使用 VBA 实际打开的 Workbook 的 namepath

我在下面的 sn-p 中尝试过,但一直收到编译器错误。

我的文档类型是.docm

我做错了什么?

我的代码sn-p:

Sub TestFileOpened()
Dim strPath As String, strPathAndName As String

    strPath = Application.ThisWorkbook.Path
    strPathAndName = strPath & Application.ThisWorkbook.Name
    MsgBox strPathAndName 

    ' Test to see if the file is open.
    If IsFileOpen(strPathAndName) Then ....

【问题讨论】:

  • ThisWorkBook 是一个 Excel 对象!你在 Word 中工作吗?
  • 谢谢你这是我的错!

标签: vba


【解决方案1】:

显然,您正在尝试使用 Word 中的一些 Excel 代码,所以首先您需要使用 Excel 应用程序:

Dim oExcel as Excel.Application
Dim wB as Excel.WorkBook
Dim strPath As String
Dim strPathAndName As String


On Error Resume Next
Set oExcel = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
    Set oExcel = CreateObject("Excel.Application")
End If
On Error GoTo 0


Set wB = oExcel.Workbooks(1)
strPath = wB.Path
strPathAndName = strPath & "\" & wB.Name
MsgBox strPathAndName 

' Test to see if the file is open.
If IsFileOpen(strPathAndName) Then ....

【讨论】:

    【解决方案2】:

    假设您想要打开的 word 文档的位置,请尝试以下操作:

    Sub TestFileOpened()
    Dim strPath As String, strPathAndName As String
    
        strPath = ThisDocument.Path
        strPathAndName = strPath & "\" & ThisDocument.Name
        MsgBox strPathAndName 
    
        ' Test to see if the file is open.
        If IsFileOpen(strPathAndName) Then ....
    

    (注意不要忘记在文件路径和名称之间添加反斜杠)

    【讨论】:

    • 谢谢!
    • 我还有一个问题,也许你可以帮助我......我做错了什么?
    • @T.Els 我不经常在 mac 上编写 vba,但你可以在这里看到:stackoverflow.com/questions/10045474/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    相关资源
    最近更新 更多