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

cmedTechnical AnalystAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Rgonzo1971Commented:
Hi,

pls try

xlWorkSheet = xlWorkBook.Sheets(xlWorkBook.Sheets.Count)

Regards
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Saurabh Singh TeotiaCommented:
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
0
cmedTechnical AnalystAuthor Commented:
@Rgonzo1971

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

Thanks
0
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Jacques Bourgeois (James Burger)PresidentCommented:
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.
0
cmedTechnical AnalystAuthor Commented:
@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.
0
Jacques Bourgeois (James Burger)PresidentCommented:
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

0
cmedTechnical AnalystAuthor Commented:
@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
0
Jacques Bourgeois (James Burger)PresidentCommented:
Cells(1,1) probably contain the String "EdConnect Log".

You should point to the cell that contains the date.
0
Rgonzo1971Commented:
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
0
cmedTechnical AnalystAuthor Commented:
@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

0
Rgonzo1971Commented:
You commented out line 3
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.