Search code examples
arraysvb.netoutlook-addin

VB.NET, Search for word length in text with a foreach returns 1 even if it is not in it


So I got this weird problem where I cant directly point out what is causing it. In my Outlook application I created an add-in (Visual Studio - VB.NET) which search for words in the body text (it searches for closing tags like regards).

These 'Closing tags' are set in an array. What it does is: Set body to the body of the text but when a closing tag is found, then just take the body text until the closing tag.

The problem however is, if the array reaches its end, and the array strings are not found, then it always runs another time (with an array of 4 it means it runs a fifth time ??) and sets the length to 1 whereas it should be 0 (not found).

The searching of the string is done with a Instr function and the cutting of the body is done with the Left function (from the point the closing tag is found).

Here the code part to make it visual:

Dim BodyText As String
            BodyText = oitem.Body

            Dim ClosingTags(4) As String
            ClosingTags(0) = "regards"
            ClosingTags(1) = "your sincerely"
            ClosingTags(2) = "yours truly"
            ClosingTags(3) = "best wishes"

            Dim MailClosing As String
            Dim BodyUntil As String

            For Each element In ClosingTags

                MailClosing = InStr(LCase(BodyText), LCase(element))

                If MailClosing <> 0 Then
                    BodyTextUntil = Left(BodyText, InStr(LCase(BodyText), LCase(element)) - 1)
                    BodyText = BodyTextUntil
                    Exit For
                Else
                    BodyText = oitem.Body
                End If

            Next element

This function works properly if a user uses a closing tag in their body. Though when they just type text without a closing tag it malfunctions. What happens then is:

  1. The foreach loops and cant find the closing tag so it keeps looping.
  2. Normally it should loop 4 times (array = 4) but when the tag is not found it somehow loops a fifth time and sets the MailClosing variable to 1, this causes the IF condition to be true while it should be false and thereby setting the body to empty (since the closing tag is found at position 1 and cuts off everything after 1 -1 = 0).

The question is, what is causing it and how to fix it? Perhaps use a for 1 - 4 (equal to the array length?)


Solution

  • Dim ClosingTags(4) As String
    

    This creates an array with 5 elements (4 is the max index, not the amount of items)

    Use 3:

    Dim ClosingTags(3) As String
    ClosingTags(0) = "regards"
    ClosingTags(1) = "your sincerely"
    ClosingTags(2) = "yours truly"
    ClosingTags(3) = "best wishes"