Forum Discussion

djmitz6's avatar
djmitz6
Copper Contributor
Feb 21, 2024

Excel Script ReplaceAll ignore formulas

Greetings,

 

I'm currently running an excel script where I am replacing all single quote characters with two single quote characters consecutively so that I can push the data in a table over to an SQL server utilizing Power Automate. One issue that I am experiencing is that when utilizing the below script it also replaces the characters inside of formulas:

// Replace SQL Reserved Characters
selectedSheet.replaceAll("'", "''", {
completeMatch: false,
matchCase: false
})

 

Example of how the formula in one of the cells originally existed:

=XLOOKUP(E4,'Sheet2'!E:E,'Sheet2'!F:F)

Example of how the formulas get formatted after running the script:

=XLOOKUP(E4,''Sheet2''!E:E,''Sheet2''!F:F)

 

Is there anyway to get the replaceAll function to ignore characters inside of formulas? I'm trying to eliminate the need to individually iterate through each cell as this is resource intensive. I also thought about just copying the range and pasting back the values only, but I feel this will also be resource intensive.

    • Lorenzo 

      That doesn't work such way. Selecting special cells we split entire range on range areas, replaceAll can't be applied to RangeAreas object.

      However, idea is great. We may iterate each area and make replacements within it

      function main(workbook: ExcelScript.Workbook) {
          workbook
          .getActiveWorksheet()
          .getUsedRange()
          .getSpecialCells(ExcelScript.SpecialCellType.constants)
          .getAreas()
          .map(a => a.getUsedRange().replaceAll("'", "''", {}))
      }
      

      Iterating cell by cell in initial range is less preferable from performance point of view.

      • Lorenzo's avatar
        Lorenzo
        Silver Contributor

        SergeiBaklan 

         

        Selecting special cells we split entire range on range areas, replaceAll can't be applied to RangeAreas object

        OK, I didn't read enough. Thanks for fixing my bad + sharing the appropriate code

  • djmitz6 

    Here's how you can modify your Excel Script to replace all single quotes while ignoring characters inside formulas:

    Option 1: Using FilterBy and ReplaceAll:

    1. Filter formulas: Use filterBy to filter out rows containing formulas:
    JavaScript
    const filteredRange = selectedSheet.getRange("A1:B10").filterBy(row => !row.getRange("A1").hasFormula());
     

    Replace A1:B10 with the actual range you want to filter and A1 with the cell containing the formula you want to check.

    1. Replace single quotes: Apply replaceAll to the filtered range:
    JavaScript
    filteredRange.replaceAll("'", "''", {
      completeMatch: false,
      matchCase: false
    });
     
    1. Optionally, replace back in the original range:
    JavaScript
    // If needed, replace back in the original range after modification
    selectedSheet.getRange("A1:B10").values = filteredRange.getValues();
     

    Option 2: Using a custom function:

    1. Define a custom function:
    JavaScript
    function replaceExceptInFormulas(text, searchValue, replaceValue) {
      // Split the text into parts based on formulas
      const parts = text.split(/={1,2}[^=]+={0,2}/);
    
      // Replace in non-formula parts
      for (let i = 0; i < parts.length; i++) {
        if (!parts[i].startsWith("=")) {
          parts[i] = parts[i].replaceAll(searchValue, replaceValue);
        }
      }
    
      // Join the parts back together
      return parts.join("");
    }
     
    1. Apply the function:
    JavaScript
    selectedSheet.getRange("A1:B10").values = selectedSheet.getRange("A1:B10").values.map(row => row.map(cell => replaceExceptInFormulas(cell, "'", "''")));
     

    Explanation:

    • Option 1: This approach filters out rows containing formulas using filterBy before applying replaceAll to avoid modifying formulas.
    • Option 2: This option defines a custom function replaceExceptInFormulas that splits the text into parts based on formulas and replaces characters only in non-formula parts.

    Both options achieve the desired result of replacing single quotes while preserving formulas. Choose the option that best suits your preference and coding style.

    Additional notes:

    • Ensure you replace A1:B10 with the actual range you want to modify.
    • Adjust the formula checking logic in Option 1 if your formulas have different patterns.
    • Consider testing the script on a small sample of data before applying it to your entire dataset.

Resources