LibreOffice 替换宏 - 只替换一次并按格式替换
LibreOffice replace macro - replace only once and replace by format
在 LibreOffice Writer 中,我想编写一个宏来查找某个字符串(例如 "abc")并将其替换为另一个字符串("def"),但是,前提是原始字符串是黑体字。此外,我只想在第一场比赛中这样做。
使用 LibreOffice 搜索和替换对话框很容易做到这一点,但是,我找不到在宏中执行此操作的方法:
首先,在 this API reference 中,我没有看到与仅查找粗体字符串相关的设置。最接近的匹配是 "SearchStyles",但这是指整个段落的样式而不是搜索词。
其次,我没有看到只替换第一次出现的命令;我只看到 "replaceAll".
有没有办法只替换粗体字,并且只替换第一个匹配项?
Andrew Pitonyak's macro document 有很多与搜索相关的好例子。以下内容改编自清单 7.41 和清单 7.45。
Sub FindBoldString
Dim oDoc As Object
Dim oSearch As Object
Dim oFound As Object
Dim srchAttributes(0) As New com.sun.star.beans.PropertyValue
oDoc = ThisComponent
oSearch = oDoc.createSearchDescriptor()
oSearch.SearchString = "abc"
oSearch.SearchRegularExpression=False
oSearch.searchStyles = True
oSearch.searchAll = False
srchAttributes(0).Name = "CharWeight"
srchAttributes(0).Value = com.sun.star.awt.FontWeight.BOLD
oSearch.SetSearchAttributes(srchAttributes)
oFound = oDoc.findFirst(oSearch)
If Not IsNull(oFound) Then
oFound.SetString("def")
oFound.CharWeight = com.sun.star.awt.FontWeight.BOLD
End If
End Sub
在 LibreOffice Writer 中,我想编写一个宏来查找某个字符串(例如 "abc")并将其替换为另一个字符串("def"),但是,前提是原始字符串是黑体字。此外,我只想在第一场比赛中这样做。
使用 LibreOffice 搜索和替换对话框很容易做到这一点,但是,我找不到在宏中执行此操作的方法:
首先,在 this API reference 中,我没有看到与仅查找粗体字符串相关的设置。最接近的匹配是 "SearchStyles",但这是指整个段落的样式而不是搜索词。
其次,我没有看到只替换第一次出现的命令;我只看到 "replaceAll".
有没有办法只替换粗体字,并且只替换第一个匹配项?
Andrew Pitonyak's macro document 有很多与搜索相关的好例子。以下内容改编自清单 7.41 和清单 7.45。
Sub FindBoldString
Dim oDoc As Object
Dim oSearch As Object
Dim oFound As Object
Dim srchAttributes(0) As New com.sun.star.beans.PropertyValue
oDoc = ThisComponent
oSearch = oDoc.createSearchDescriptor()
oSearch.SearchString = "abc"
oSearch.SearchRegularExpression=False
oSearch.searchStyles = True
oSearch.searchAll = False
srchAttributes(0).Name = "CharWeight"
srchAttributes(0).Value = com.sun.star.awt.FontWeight.BOLD
oSearch.SetSearchAttributes(srchAttributes)
oFound = oDoc.findFirst(oSearch)
If Not IsNull(oFound) Then
oFound.SetString("def")
oFound.CharWeight = com.sun.star.awt.FontWeight.BOLD
End If
End Sub