如何创建一个按钮来在VB.NET中打开以前的Excel工作表?

时间:2019-02-01 21:07:17

标签: excel vb.net

我想创建一个按钮来打开以前打开的excel工作表。您的想法是什么?

VBA中有一个代码:Sheet(ActiveSheet.previos.Activate).select

我试图将其翻译成vb.NET,但是没有用。

Dim ActiveWorkSheet As Microsoft.Office.Interop.Excel.Worksheet=

Globals.ThisWorkbook.Application.Activeworkbook.Worksheet(ActiveWorkSheet.Previous).select()

1 个答案:

答案 0 :(得分:0)

(答案1)您可以尝试以下操作,因为它将最后一页存储到工作簿中。进行此操作后,请确保删除msgbox。我将以下代码放入Excel的ThisWorkBook对象中。


Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Dim docProp As DocumentProperty
    Dim strSheet As String

    With ThisWorkbook
        If .CustomDocumentProperties.Count > 0 Then
            For Each docProp In .CustomDocumentProperties
                If LCase(Trim(docProp.Name)) = "previoussheet" Then
                    strSheet = .ActiveSheet.Name
                    docProp.Value = strSheet

                    MsgBox "Worksheet (" & strSheet & ") has been saved."

                    Exit For
                End If
            Next
        Else
            .CustomDocumentProperties.Add "PreviousSheet", False, msoPropertyTypeString, ThisWorkbook.ActiveSheet.Name
        End If
    End With
End Sub

Private Sub Workbook_Open()
  Dim wrk As Workbook
  Dim docProp As DocumentProperty
  Dim strSheet As String

  Set wrk = ThisWorkbook

  If wrk.CustomDocumentProperties.Count > 0 Then
      For Each docProp In wrk.CustomDocumentProperties
          If LCase(Trim(docProp.Name)) = "previoussheet" Then
              strSheet = docProp.Value
              wrk.Worksheets(strSheet).Select
              MsgBox "Worksheet " & strSheet & " has been selected."
              Exit For
          End If
      Next
  End If

  Set wrk = Nothing
End Sub

(答案2)您可以尝试执行此操作。但是,您将需要使用下面的对象打开工作簿,然后将该变量(objExcel)保留在内存中,直到完成操作为止。 vba要求set关键字,但是如果在vb.net中执行此操作,则可以删除set关键字,然后在完成该操作后就可以将对象设置为等于空。这是代码:

    Public objExcel As Object
    Dim strSheet as string
    Dim intSheet as integer

    Public Sub GetPrevSheet()
        Dim intI as integer

        Set objExcel = CreateObject("Excel.Application")

        strSheet = objExcel.ActiveWorkbook.ActiveSheet.Name
        'Find the sheet with the same name as the active sheet
        for intI = 1 to objExcel.Activeworkbook.Worksheets.count
            if lcase(trim(strsheet)) = _
               lcase(trim(objExcel.ActiveWorkbook.Worksheet(inti).name)) then
                intSheet = intI
                exit for
            End if
        next intI

        'Go back 1 and then select it.
        if intSheet > 1 then intSheet = intSheet - 1

        objExcel.Activeworkbook.Worksheets(intSheet).select

        Set objExcel = Nothing

    End Sub