应用条件格式-重复项- Excel Javascript

uplii1fm  于 2023-01-14  发布在  Java
关注(0)|答案(2)|浏览(123)

我试图通过Office-JS向Excel中的列添加条件突出显示。我第一次使用automate功能,但似乎无法在Excel中使用它。
这是automate的结论:

function main(workbook: ExcelScript.Workbook) {
    let conditionalFormatting: ExcelScript.ConditionalFormat;
    let selectedSheet = workbook.getActiveWorksheet();
    // Change preset criteria from range A:A on selectedSheet
    conditionalFormatting = selectedSheet.getRange("A:A").addConditionalFormat(ExcelScript.ConditionalFormatType.presetCriteria);
    conditionalFormatting.getPreset().getFormat().getFont().setColor("#9C0006");
    conditionalFormatting.getPreset().getFormat().getFill().setColor("#FFC7CE");
    conditionalFormatting.getPreset().setRule({criterion: ExcelScript.ConditionalFormatPresetCriterion.duplicateValues,});
}

这是我试图抄录的内容:

function Do_ApplyHighlightDupsConditionalFormatting(rng) {
    ConditionalFormat.rng.addConditionalFormat(ExcelScript.ConditionalFormatType.presetCriteria);
    ConditionalFormat.getPreset().getFormat().getFont().setColor("#9C0006");
    ConditionalFormat.getPreset().getFormat().getFill().setColor("#FFC7CE");
    ConditionalFormat.getPreset().setRule({ criterion: ExcelScript.ConditionalFormatPresetCriterion.duplicateValues, });
}
pftdvrlh

pftdvrlh1#

您可以使用ConditionalFormatPresetCriterion执行此操作。请参阅以下示例:

$("#run").click(() => tryCatch(run));
    
    async function run() {
      await Excel.run(async (context) => {
        const wb: Excel.Workbook = context.workbook;
        const ws: Excel.Worksheet = wb.worksheets.getActiveWorksheet();
        const rang: Excel.Range = ws.getRange("A1:A5");
        const cf: Excel.ConditionalFormat = rang.conditionalFormats.add(Excel.ConditionalFormatType.presetCriteria);
        cf.preset.format.font.color = "red";
      cf.preset.rule = {criterion:Excel.ConditionalFormatPresetCriterion.duplicateValues};
    
        await context.sync();
    
      });
    }
    
    /** Default helper for invoking an action and handling errors. */
    async function tryCatch(callback) {
      try {
        await callback();
      } catch (error) {
        // Note: In a production add-in, you'd want to notify the user through your add-in's UI.
        console.error(error);
      }
    }
ryoqjall

ryoqjall2#

在调换了the MS Docs和@BrianGonzalez打字答案之后,我让它工作了!
功能:

function Set_Dup_Conditional_Formatting(rng) {
    //https://stackoverflow.com/questions/71189904/apply-conditional-formatting-duplicates-excel-javascript
    var conditionalFormat = rng.conditionalFormats.add(
        Excel.ConditionalFormatType.presetCriteria
    );
    conditionalFormat.preset.format.font.color = "red";
    conditionalFormat.preset.rule = {
        criterion: Excel.ConditionalFormatPresetCriterion.duplicateValues
    };
    return true;
}

相关问题