Page 1 of 1

[Solved] Function and returned object

PostPosted: Thu Jun 14, 2018 9:08 pm
by Mr.Dandy
Hello,

I have a function in Calc that collect a CellRange structure and an createseachdescriptor object.
How can I return these into one single object?

Re: Function and returned object

PostPosted: Thu Jun 14, 2018 10:40 pm
by Lupp
In Basic you can mainly use an array (with variant elements), a structure of defined (specialised) type or a collection, I think.

In your case a collection might be appropriate. See example code:
Code: Select all   Expand viewCollapse view
Function createRangeWithSearchD()
theSheet    = ThisComponent.Sheets(0)
myRange     = theSheet.GetCellRangeByName("D5:G12")
sDRange     = myRange.CreateSearchDescriptor()
With sDRange
  .SearchRegularExpression = True
  REM Additional settings may follow.
End With
Dim myCollection As New Collection
myCollection.Add(myRange, "theRange")
myCollection.Add(sDRange, "theSD")
createRangeWithSearchD = myCollection
End Function


Sub test()
REM A rather absurd example. But it works!
coll = createRangeWithSearchD()
coll.Item("theSD").SearchString = "^1.*$"
firstFinding = coll.Item("theRange").findFirst(coll.Item("theSD"))
End Sub


One strange thing: Instead of using the keystrings assigned with the .Add method you can also use an index. It is 1-based!

Editing: I missed to state that I only recently learned about the Basic 'Class' Collection from user JeJe.

Re: Function and returned object

PostPosted: Fri Jun 15, 2018 7:25 am
by JeJe
I presume you know this and have a reason for wanting to pack everything into the function return - but in case you don't - its not necessary. If you pass objects/variable to the sub or function in the declaration - then you can use the return value to tell you whether the function succeeded or not. If the return value is a simple number then its often used for both purposes (eg 0 or -1 or another set value if the function fails, anything else and it succeeded)


Code: Select all   Expand viewCollapse view
'with some help from Lupp's above example
sub test2()
   dim theRange as object,SearchDescriptor as object,succeed as boolean
   succeed = MYfunction(ThisComponent.Sheets(0),"D5:G12",therange,searchdescriptor)
   if succeed then
   msgbox searchdescriptor.SearchRegularExpression
      'do something

   end if
end sub

function MYfunction(Thesheet as object,rangeExpression as string, theRange as object,SearchDescriptor as object) as boolean
on error goto errorhandler:
   theRange = theSheet.GetCellRangeByName(rangeExpression)
   SearchDescriptor = theRange.CreateSearchDescriptor()
   SearchDescriptor.SearchRegularExpression = True
   MYfunction = true
errorhandler:
   'exits with MYfunction = false
end function


Re: Function and returned object

PostPosted: Sat Jun 16, 2018 3:20 pm
by Mr.Dandy
Thanks for your explanations

Solved!