How to format string in cell in Calc

Creating a macro - Writing a Script - Using the API (OpenOffice Basic, Python, BeanShell, JavaScript)
Post Reply
adikowo
Posts: 1
Joined: Sun Jan 10, 2010 12:28 pm

How to format string in cell in Calc

Post by adikowo »

I was looking in google and on this forum and I couldn't find how to format string in cell in Calc.
What I need is to change all text in brackets to italic:
For example in cell B1 I have a text:
(name) Abrakadabra [abc]
and I want to have
(name) Abrakadabra [abc]
I thing it is no possible to be done using normal Replace method from Calc. I couldn't also find how to do it using Macros.
OpenOffice 3.1.1 on Win XP / OpenOffice 3.1.1 Kubuntu 9.04
hanya
Volunteer
Posts: 885
Joined: Fri Nov 23, 2007 9:27 am
Location: Japan

Re: How to format string in cell in Calc

Post by hanya »

Use text cursor to format the part of a cell.

This example does not support multiply braced string.

Code: Select all

Sub search_brackets
  oDoc = ThisComponent
  oSheet = oDoc.getCurrentController().getActiveSheet()
  
  oDesk = oSheet.createSearchDescriptor()
  With oDesk
    .SearchString = "\(.+?\)|\{.+?\}|\[.+?\]"
    .SearchRegularExpression = True
  End With
  
  ' regexp search inside cell text
  oTextSearch = CreateUnoService("com.sun.star.util.TextSearch")
  oOptions = CreateUnoStruct("com.sun.star.util.SearchOptions")
  With oOptions
    .algorithmType = com.sun.star.util.SearchAlgorithms.REGEXP
    .searchString = "(\(([^\)]+?)\)|\{([^\}]+?)\}|\[([^\]]+?)\])"
  End With
  oTextSearch.setOptions(oOptions)
  
  ' search cells
  oFound = oSheet.findFirst(oDesk)
  While NOT IsNull(oFound)
    BrasedtoItalic(oFound, oTextSearch)
    oFound = oSheet.findNext(oFound, oDesk)
  WEnd
End Sub


Sub BrasedtoItalic(oCell As Object, oTextSearch As Object)
  nItalic = com.sun.star.awt.FontSlant.ITALIC
  If NOT IsNull(oCell) Then
    sStr = oCell.getString()
    oCursor = oCell.createTextCursor()
    oFound = oTextSearch.searchForward(sStr, 0, Len(sStr))
    While oFound.subRegExpressions > 0
      If oFound.subRegExpressions > 2 Then
        nStart = oFound.startOffset()
        nEnd = oFound.endOffset()
        'msgbox Mid(sStr, nStart(2) +1, nEnd(2) - nStart(2))
        With oCursor
          .gotoStart(False)
          .goRight(nStart(2), False)
          .goRight(nEnd(2) - nStart(2), True)
          .CharPosture = nItalic
        End With
        oFound = oTextSearch.searchForward(sStr, nEnd(2) +1, Len(sStr))
      Else
        Exit Sub
      End If
    WEnd
  End If
End Sub
Please, edit this thread's initial post and add "[Solved]" to the subject line if your problem has been solved.
Apache OpenOffice 4-dev on Xubuntu 14.04
Post Reply