簡體   English   中英

如何創建一個按鈕來在VB.NET中打開以前的Excel工作表?

[英]How to create a Button that opens the previous excel sheet in 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)您可以嘗試以下操作,因為它將最后一頁存儲到工作簿中。 進行此操作后,請確保刪除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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM