vb.net 获取活动 Excel 工作簿的完整路径和文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19903203/
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-17 15:46:39  来源:igfitidea点击:

vb.net get full path and filename of active excel workbook

vb.netvisual-studio-2010excel

提问by rogue5pawn

I had this code working a few days ago, but forgot to save the working copy. It took me 4 weeks just to find this answer and would not like to take that much time again, so...

几天前我让这段代码工作,但忘记保存工作副本。我花了 4 周才找到这个答案,不想再花那么多时间,所以......

Everything here works, except the objWorkBooklines, which return the error: "Variable 'objWorkBook' is used before it has been assigned a value. A null reference exception could result at runtime."

除了objWorkBook行之外,这里的所有内容都可以正常工作,该行返回错误:“变量 'objWorkBook' 在被分配值之前被使用。在运行时可能会导致空引用异常。”

Any suggestions?

有什么建议?

Dim objExcel As Excel.Application = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
Dim objWorkBook As Excel.Workbook

Dim totalWorkBooks As Integer = objExcel.Workbooks.Count
MsgBox(totalWorkBooks & " is Number of Open Workbooks")

Dim ActiveBookIndex As Integer = objExcel.ActiveWindow.Index
MsgBox(ActiveBookIndex & " is Active Window Index")

Dim FullName As String = objWorkBook.FullName
MsgBox(FullName & " is FullName")

Dim OnlyName As String = objWorkBook.Name
MsgBox(OnlyName & " is Name without the Path")

I forgot what Value I had assigned.

我忘记了我分配的价值。

My objective is to compare an open Excel Workbook name with one in a known location so that if they match, my program can proceed. I need the code above so I can compare it to the following code in an If-Then so that my program can proceed.

我的目标是将打开的 Excel 工作簿名称与已知位置的名称进行比较,以便如果它们匹配,我的程序就可以继续。我需要上面的代码,以便我可以将它与 If-Then 中的以下代码进行比较,以便我的程序可以继续。

Dim dir As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Dim FullFileName As String = dir & "\My_File_Name.xlsx"

On a positive note, I pieced together A solution, even though it's not the answer I was looking for....

从积极的方面来说,我拼凑了一个解决方案,即使这不是我想要的答案......

Dim p() As Process = System.Diagnostics.Process.GetProcessesByName("Excel")
Dim Title As String = p(0).MainWindowTitle
Dim dir As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
        Dim FullFileName As String = dir & "\" & Replace(Title, "Microsoft Excel - ", "") & ".xlsx"

MsgBox(dir)
MsgBox(Title)
MsgBox(FullFileName)

This will work for now, but I would like to solve it the other way.

这暂时有效,但我想以另一种方式解决它。

采纳答案by Siddharth Rout

Change the line

换线

Dim objWorkBook As Excel.Workbook

Dim objWorkBook As Excel.Workbook

to

Dim objWorkBook As Excel.Workbook = Nothing

Dim objWorkBook As Excel.Workbook = Nothing

Also your objWorkBookobject is not assigned to anything before you are trying to use it in the line Dim FullName As String = objWorkBook.FullName

objWorkBook在您尝试在行中使用它之前,您的对象也没有分配给任何东西Dim FullName As String = objWorkBook.FullName

Is this what you are trying?

这是你正在尝试的吗?

Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim objExcel As Excel.Application = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
        Dim objWorkBook As Excel.Workbook

        Dim totalWorkBooks As Integer = objExcel.Workbooks.Count
        MsgBox (totalWorkBooks & " is Number of Open Workbooks")

        Dim ActiveBookIndex As Integer = objExcel.ActiveWindow.Index
        MsgBox (ActiveBookIndex & " is Active Window Index")

        '~~> Set the workbook to say first workbook.
        '~~> You can use a loop here as well to loop through 
        '~~> the workbooks count
        objWorkBook = objExcel.Workbooks(1)

        Dim FullName As String = objWorkBook.FullName
        MsgBox (FullName & " is FullName")

        Dim OnlyName As String = objWorkBook.Name
        MsgBox (OnlyName & " is Name without the Path")

        '
        '~~> Rest of the code
        '
    End Sub
End Class

EDIT: Followup from comments

编辑:评论的跟进

But let's say I have 9 Workbooks already open, how do I get me app to index, manipulate, switch between them... without knowing the Full Path and File Names ahead of time?

但是,假设我已经打开了 9 个工作簿,如何让我的应用程序在它们之间建立索引、操作、切换......而无需提前知道完整路径和文件名?

Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim objExcel As Excel.Application = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
        Dim objWorkBook As Excel.Workbook = Nothing
        Dim FullName As String = ""
        Dim OnlyName As String = ""

        Dim totalWorkBooks As Integer = objExcel.Workbooks.Count
        MsgBox (totalWorkBooks & " is Number of Open Workbooks")

        For i As Integer = 1 To totalWorkBooks
            objWorkBook = objExcel.Workbooks(i)

            With objWorkBook
                FullName = .FullName
                OnlyName = .Name

                MessageBox.Show (FullName & " is FullName and " & OnlyName & " is Name without the Path")

                '
                '~~> Rest of the code here to manipulate the workbook. For example
                ' objWorkBook.Sheets(1).Range("A1").Value = "Blah Blah"
                '

            End With
        Next i

        releaseObject (objExcel)
        releaseObject (objWorkBook)
    End Sub

    '~~> Release the objects
    Private Sub releaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject (obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub
End Class