仅在选定单元格上运行现有宏,而不是整个工作表

时间:2014-03-13 18:41:24

标签: vba libreoffice libreoffice-calc

我有以下宏(LibreOffice Calc):

Sub CalcFindAndReplace
    Dim oDoc,aFind,aReplace,aRayCount,FandR,oSheet
    oDoc = ThisComponent
    aFind = Array("Mecanica","Cancion","Murcielago")
    aReplace = Array("Mecánica","Canción","Murciélago")
    aRayCount = 0
    oSheet = oDoc.getSheets.getByName(oDoc.CurrentSelection.Spreadsheet.Name)
    FandR = oSheet.createReplaceDescriptor
    FandR.SearchCaseSensitive = true
    FandR.SearchWords = true ' 1 to A but not 11 to AA
    FandR.SearchRegularExpression = true

    While aRayCount <= uBound(aFind)
        FandR.setSearchString(aFind(aRayCount))
        FandR.setReplaceString(aReplace(aRayCount))
        aRayCount = aRayCount + 1
        oSheet.ReplaceAll(FandR)
    End While

End Sub

它工作正常,但我需要添加它才能仅应用于手动选择单元格(每次不同),而不是在工作表的所有单元格上。

1 个答案:

答案 0 :(得分:0)

EDITED

以下代码将采用当前选定的单元格,将用实际的String值替换每个单元格(注意:可能作用于单元格的calc函数将永久删除),然后根据需要替换字符串单元格。

http://www.oooforum.org/forum/viewtopic.phtml?t=137064http://www.oooforum.org/forum/viewtopic.phtml?t=71015以及http://www.oooforum.org/forum/viewtopic.phtml?t=65318 ...

激励
Sub ReplaceEachCellWithActualValue()
    ' Gets the current user selection and replace each cell with the actual String value
    Dim oDoc, oSheet, oCell As Object
    oDoc = ThisComponent
    oSheet = oDoc.getSheets.getByName(oDoc.CurrentSelection.Spreadsheet.Name)
    RangeAddress = oDoc.getCurrentSelection.getRangeAddress 

    c1 = RangeAddress.StartColumn
    r1 = RangeAddress.StartRow
    c2 = RangeAddress.EndColumn
    r2 = RangeAddress.EndRow

    for i = c1 to c2
            for j = r1 to r2 
                    Dim cellasstring As String
                    oCell = oSheet.getCellByPosition(i, j)
                    cellasstring = oCell.string
                    oSheet.getCellByPosition(i, j).String = cellasstring
            next j
    next i

End Sub

Sub CalcFindAndReplace

    ' first replace all formulas on the selected cells with actual strings...
    ReplaceEachCellWithActualValue()

    ' Then replace as desired...  
    Dim oDoc,aFind,aReplace,aRayCount,FandR,oSheet        
    oDoc = ThisComponent
    aFind = Array("Mecanica","Cancion","Murcielago")
    aReplace = Array("Mecánica","Canción","Murciélago")
    aRayCount = 0
    oSheet = oDoc.getSheets.getByName(oDoc.CurrentSelection.Spreadsheet.Name)
    FandR = oSheet.createReplaceDescriptor
    FandR.SearchCaseSensitive = true
    FandR.SearchWords = true ' 1 to A but not 11 to AA
    FandR.SearchRegularExpression = true

    Dim oSelection as Object
    oSelection = oDoc.CurrentController.getSelection

    While aRayCount <= uBound(aFind)
        FandR.setSearchString(aFind(aRayCount))
        FandR.setReplaceString(aReplace(aRayCount))
        oSelection.ReplaceAll(FandR) 
        aRayCount = aRayCount + 1
    Wend
End Sub