Question

I need help in writing a macro for LibreOffice Calc 3.6.2.2

What I'm trying to do is pass a cell number to function, the function then analyzes the cell's contents (a text string) and return a value based on its content.

My current code:

Function mColor2(mCellAdd)

    Dim l(5) as String 'declare list of variables

    l(0)="red"
    l(1)="blue"
    l(2)="yellow"
    l(3)="green"


    for i=LBound(l) To UBound(l) 'cycle from start to end of list 

        If InStr(mCellAdd,l(i))<>0 Then
            mColor2=l(i)
        Else
            mColor2="not known" 
        End If

    Next        


End Function

But I get only "not known" returned.

I think it's because I don't handle values returned from InStr() properly.

Actually I'm not sure I'm using the right function since I only need to check if the cell's content includes my substring or not...

A screenshot of the results:

Was it helpful?

Solution

Let's say the input string (assuming it is passed as a string?) is "my blue dog". Then your function will run through the loop 5 times (should that be 4?). First it looks for "red", which isn't found, so mColor2 is set to "not known". Then it looks for "blue", which is found, so mColor2 is set to "blue". Then it looks for "yellow", and mColor2 is set back to "not known". Same for "green", and then I don't know what it will look for when i is 4.

In any case, you don't want to reset mColor2 to "not known", just get rid of your Else.

Have you decided what to do if the input string contains more than one of the strings you're looking for? Do you want to exit as soon as you find "red", or continue and remember the last one found?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top