如何将活动的Excel工作簿和活动的Excel工作表声明为变量?

时间:2015-11-03 18:56:43

标签: vb.net

我试图想出如何将活动工作簿和活动工作表设置为我稍后可以参考的变量。我已经设置了我的脚本,并且我将????放在我认为可以放置参考的区域。

任何建议?

  Dim oXL As Application
        Dim oWB As Microsoft.Office.Interop.Excel.Workbook
        Dim oSheet As Microsoft.Office.Interop.Excel.Worksheet
        Dim oRng As Microsoft.Office.Interop.Excel.Range

        oWB = ????
        oSheet = ?????

将评论信息添加到Karen Payne的回答中:

  

我试图引用一个已经打开的现有的,即   使用我的应用程序时的活动窗口。

即:如何附加到打开的Excel实例并检索对ActiveWorkbook的引用?

5 个答案:

答案 0 :(得分:1)

也许以下内容会有所帮助。这是一个演示,可以在xlWorkSheet中设置可以根据需要使用的活动工作表。

Option Strict On
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports System.Runtime.InteropServices

Module SetDefaultWorkSheetCode
    Public Sub SetDefaultSheet(ByVal FileName As String, ByVal SheetName As String)
        Dim xlApp As Excel.Application = Nothing
        Dim xlWorkBooks As Excel.Workbooks = Nothing
        Dim xlWorkBook As Excel.Workbook = Nothing
        Dim xlWorkSheet As Excel.Worksheet = Nothing
        Dim xlWorkSheets As Excel.Sheets = Nothing

        xlApp = New Excel.Application
        xlApp.DisplayAlerts = False
        xlWorkBooks = xlApp.Workbooks
        xlWorkBook = xlWorkBooks.Open(FileName)

        xlApp.Visible = False
        xlWorkSheets = xlWorkBook.Sheets

        For x As Integer = 1 To xlWorkSheets.Count
            xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)

            If xlWorkSheet.Name = SheetName Then

                xlWorkSheet.Activate()

                xlWorkSheet.SaveAs(FileName)
                Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
                xlWorkSheet = Nothing

                Exit For

            End If

            Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
            xlWorkSheet = Nothing

        Next

        xlWorkBook.Close()
        xlApp.UserControl = True
        xlApp.Quit()

        ReleaseComObject(xlWorkSheets)
        ReleaseComObject(xlWorkSheet)
        ReleaseComObject(xlWorkBook)
        ReleaseComObject(xlWorkBooks)
        ReleaseComObject(xlApp)

    End Sub
    Private Sub ReleaseComObject(ByVal obj As Object)
        Try
            If obj IsNot Nothing Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
                obj = Nothing
            End If
        Catch ex As Exception
            obj = Nothing
        End Try
    End Sub

End Module

答案 1 :(得分:0)

使用这些Excel对象,您必须使用“Set”关键字为它们指定值。例如:

Set oWB = ActiveWorkbook

答案 2 :(得分:0)

以下是两种附加到正在运行的Excel实例的技术。我认为' Button1_Click'中显示的方法是你正在寻找的,但我也展示了第二种方法,它在运行对象表(ROT)中查找匹配的工作簿名称。

Imports System.Runtime.InteropServices
Imports Microsoft.Office.Interop

Public Class Form1
    Private WithEvents ExcelCleanUpTimer As New Timer With {.Interval = 100}

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim app As Excel.Application
        Try ' to attach to any Excel instance
            app = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
        Catch ex As Exception
            MessageBox.Show("No Excel instances found")
            Exit Sub
        End Try

        ' take over responsibility for closing Excel
        app.UserControl = False
        app.Visible = False

        Dim activeWB As Excel.Workbook = app.ActiveWorkbook

        Dim activeSheet As Object = app.ActiveSheet

        ' determine if ActiveSheet is a Worksheet or Chart
        ' if it is a Worksheet, activeChart is Nothing
        ' if it is a Chart, activeWorksheet is Nothing
        Dim activeWorksheet As Excel.Worksheet = TryCast(activeSheet, Excel.Worksheet)
        Dim activeChart As Excel.Chart = TryCast(activeSheet, Excel.Chart)

        If activeWorksheet IsNot Nothing Then
            For Each cell As Excel.Range In activeWorksheet.Range("A1:A20")
                cell.Value2 = "hello"
            Next
        End If

        'shut Excel down, don't save anything
        app.DisplayAlerts = False
        app.Workbooks.Close()
        app.Quit()

        ' using a timer lets any ComObj variables in this method go out of context and
        ' become eligible for finalization.  GC's call to RCW wrapper finalizer will 
        ' release its reference counts on Excel
        ExcelCleanUpTimer.Start()
    End Sub

    Private Sub ExcelCleanUpTimer_Tick(sender As Object, e As EventArgs) Handles ExcelCleanUpTimer.Tick
        ExcelCleanUpTimer.Stop()
        GC.Collect()
        GC.WaitForPendingFinalizers()
    End Sub


    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ' if this is a saved Workbook, the path will be the full file path
        Dim path As String = "Book1" ' or the full file path to a workbook including the extension

        Dim activeWorkbook As Excel.Workbook = Nothing
        Try
            ' this technique differs for Marshal.GetActiveObject in that if the path 
            ' is a valid file path to an Excel file and Excel is not running, it will
            ' launch Excel to open the file.
            activeWorkbook = CType(Marshal.BindToMoniker(path), Excel.Workbook)
        Catch ex As Exception
            ' an exception will be throw if 'path' is not found in the Runinng Object Table (ROT)
            MessageBox.Show(path & " not found")
            Exit Sub
        End Try

        Dim app As Excel.Application = activeWorkbook.Application
        app.Visible = True
        app.UserControl = True

        ' the wb window will be hidden if opening a file
        activeWorkbook.Windows(1).Visible = True


        ExcelCleanUpTimer.Start()
    End Sub
End Class

答案 3 :(得分:0)

对不起我的上一个答案..我没有看到你在.NET中尝试这样做。无论如何,就像在Excel的上下文中一样,您必须首先打开或创建您想要使用的所有工作簿。如果已经打开它,则可以使用要将其分配给工作簿变量的工作簿的文件名。

xlWorkbook = xlApp.Workbooks.Item("filename of the workbook already open")

答案 4 :(得分:0)

以下是相同的代码,部分注释了激活部分,我在代码中添加了以显示如何获取当前活动工作表。

    Option Strict On
    Imports Excel = Microsoft.Office.Interop.Excel
    Imports Microsoft.Office
    Imports System.Runtime.InteropServices

Module SheetCode
        Public Sub SetDefaultSheet(ByVal FileName As String, ByVal SheetName As String)
            Dim xlApp As Excel.Application = Nothing
            Dim xlWorkBooks As Excel.Workbooks = Nothing
            Dim xlWorkBook As Excel.Workbook = Nothing
            Dim xlWorkSheet As Excel.Worksheet = Nothing
            Dim xlWorkSheets As Excel.Sheets = Nothing

            xlApp = New Excel.Application
            xlApp.DisplayAlerts = False
            xlWorkBooks = xlApp.Workbooks
            xlWorkBook = xlWorkBooks.Open(FileName)

            xlApp.Visible = False
            xlWorkSheets = xlWorkBook.Sheets
            '
            ' Here I added how to get the current active worksheet
            '
            Dim ActiveSheetInWorkBook As Excel.Worksheet = CType(xlWorkBook.ActiveSheet, Excel.Worksheet)
            Console.WriteLine(ActiveSheetInWorkBook.Name)

            Runtime.InteropServices.Marshal.FinalReleaseComObject(ActiveSheetInWorkBook)
            ActiveSheetInWorkBook = Nothing

            'For x As Integer = 1 To xlWorkSheets.Count
            '    xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
            '    If xlWorkSheet.Name = SheetName Then

            '        xlWorkSheet.Activate()

            '        xlWorkSheet.SaveAs(FileName)
            '        Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
            '        xlWorkSheet = Nothing

            '        Exit For

            '    End If

            '    Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
            '    xlWorkSheet = Nothing

            'Next

            xlWorkBook.Close()
            xlApp.UserControl = True
            xlApp.Quit()

            ReleaseComObject(xlWorkSheets)
            ReleaseComObject(xlWorkSheet)
            ReleaseComObject(xlWorkBook)
            ReleaseComObject(xlWorkBooks)
            ReleaseComObject(xlApp)

        End Sub
        Private Sub ReleaseComObject(ByVal obj As Object)
            Try
                If obj IsNot Nothing Then
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
                    obj = Nothing
                End If
            Catch ex As Exception
                obj = Nothing
            End Try
        End Sub

    End Module