Link to home
Start Free TrialLog in
Avatar of cmed
cmed

asked on

How can I find and use the last sheet in the worksheet in vb.net

Hello Experts,

I am trying to write a code to find the last worksheet in my workbook instead calling a specific sheet because the worksheet changes everyday.  Right now I am calling a specific sheet

xlWorkSheet = xlWorkBook.Sheets("April 13, 2015")


Private Sub CompletedDownloadEmail()
        xlWorkBook = xlApp.Workbooks.Open("S:\ED CONNECT LOG\April 2015.xlsx")
        xlWorkSheet = xlWorkBook.Sheets("April 13, 2015")


        xlRange = xlWorkSheet.UsedRange
        MailItem = Outlook.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem)
        oInsp = MailItem.GetInspector
        MailItem.Display()
        SigString = Environ("appdata") & _
                "\Microsoft\Signatures\Calvin Scroggins 2.htm"
        If Dir(SigString) <> "" Then
            Signature = GetBoiler(SigString)
        Else
            Signature = ""
        End If
        With MailItem
            .HTMLBody = String.Format("{0}{1}", RangetoHTML(xlRange), Signature)
            .Subject = String.Format("Completed ISIR Downloads {0:M/dd}", Date.Now)
            .Recipients.Add("ISIR Downloads")
            '.Send()
        End With
        xlWorkBook.Close(False)
        xlApp.Quit()

        '~~> Clean Up
        releaseObject(xlApp)
        releaseObject(xlWorkBook)
    End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Rgonzo1971
Rgonzo1971

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Change this line to...

xlWorkSheet = xlWorkBook.Sheets("April 13, 2015")

Open in new window


To this...

xlWorkSheet = xlWorkBook.Sheets(sheets.count)

Open in new window


This will automatically make the lastsheet in xlworksheet
Avatar of cmed
cmed

ASKER

@Rgonzo1971

I tried this before I ask for help and I was trying to use worksheet instead of sheets.

Thanks
Be careful. Are you looking for the last sheet created or the rightmost sheet in the workbook?

Sheets(sheets.count) will give you the last worksheet according to their location in the workbook. If somebody moves the sheets around, the last one created might not end up as being as sheets.count.

As for the difference between Sheets and Worksheets...

Most of the time, they are interchangeable.

However, Sheets is a remainder of Excel 4, the first application in which VBA was incorporated. The whole stuff was later revised, bringing new ways of working with VBA and OLE, and the Worksheet replaced the Sheet. So Worksheet is usually preferable.

One of the things that was wrong with Sheet is that in their standard, Microsoft give all VBA objects in the Office suite the same name as the one used in the documentation. A Word document is a Document object. A workbook becomes a Workbook object. But a worksheet was first brought as a Sheet object, thus using a different word for the object manipulated by the user and the object manipulated by the code.

Sheet also does not follows today's ways of instantiating objects. Just try to compile or run the following:

Dim x As New Worksheet
Dim z As New Sheet

You will see that New Worksheet works while New Sheet gives an error. This is because the use of the constructor (New) was not introduced yet when the Sheet object was created. It came later, becoming, as in most object languages, the way to instantiate an object in VBA.
Avatar of cmed

ASKER

@James

I am actually looking for the last worksheet created, but I am the person that creates the worksheet each day.  The code that I am using at the moment look for the rightmost worksheet, which should be the last worksheet.  I understand your point, but I do not have a code that look for the last worksheet created.  I can try to see what I can come up with.  

Thanks again for your expertise.
If you create the sheet yourself, then you could insert the date in a given cell. This could even be done automatically through the NewSheet event in ThisWorkbook:

Private Sub Workbook_NewSheet(ByVal Sh As Object)
  Sh.Cells(1, 1).Value = Date
End Sub

Open in new window


You could then loop through the worksheets to find the one that has the latest date.

Sub GoToLastSheet()

  Dim target As Worksheet
  Dim sheet As Worksheet
  Dim lastDate As Date
  
  For Each sheet In Worksheets
    If sheet.Cells(1, 1).Value > lastDate Then
      lastDate = sheet.Cells(1, 1).Value
      Set target = sheet
    End If
  Next
  
  target.Activate
  
End Sub

Open in new window

Avatar of cmed

ASKER

@James

When I run the sub I get this error message

Conversion from string "EdConnect Log" to type 'Date' is not valid.

on this line

If sheet.Cells(1, 1).Value > lastDate Then
Cells(1,1) probably contain the String "EdConnect Log".

You should point to the cell that contains the date.
HI,

pls try
Sub GoToLastSheet()

  Dim target As Worksheet
  Dim sheet As Worksheet
  Dim lastDate As Date
  
  For Each sheet In Worksheets
    If IsDate(sheet.name) Then
    If DateValue(sheet.name) > lastDate Then
      lastDate = DateValue(sheet.name)
      Set target = sheet
    End If
    End If
  Next
  
  target.Activate
  
End Sub

Open in new window

Regards
Avatar of cmed

ASKER

@Rgonzo

When I ran your code the sub work but now I am getting an error message on this line

 xlRange = xlWorkSheet.UsedRange Line 7

The error message:

Object reference not set to an instance of an object.

Private Sub CompletedDownloadEmail()
        xlWorkBook = xlApp.Workbooks.Open("S:\E<wbr ></wbr>D CONNECT LOG\April 2015.xlsx")
        'xlWorkSheet = xlWorkBook.Sheets(xlWorkBo<wbr ></wbr>ok.Sheets.<wbr ></wbr>Count)

        GoToLastSheet()
      
        xlRange = xlWorkSheet.UsedRange
        MailItem = Outlook.CreateItem(Microso<wbr ></wbr>ft.Office.<wbr ></wbr>Interop.Ou<wbr ></wbr>tlook.OlIt<wbr ></wbr>emType.olM<wbr ></wbr>ailItem)
        oInsp = MailItem.GetInspector
        MailItem.Display()
        SigString = Environ("appdata") & _
                "\Microsoft\Signatures\Cal<wbr ></wbr>vin Scroggins 2.htm"
        If Dir(SigString) <> "" Then
            Signature = GetBoiler(SigString)
        Else
            Signature = ""
        End If
        With MailItem
            .HTMLBody = String.Format("{0}{1}", RangetoHTML(xlRange), Signature)
            .Subject = String.Format("Completed ISIR Downloads {0:M/dd}", Date.Now)
            .Recipients.Add("ISIR Downloads")
            '.Send()
        End With
        xlWorkBook.Close(False)
        xlApp.Quit()

        '~~> Clean Up
        releaseObject(xlApp)
        releaseObject(xlWorkBook)
    End Sub

Open in new window

You commented out line 3