I would like to specify a conditional format for Excel in C#.

Asked 2 years ago, Updated 2 years ago, 52 views

Open an Excel file already created with c#, specify a range, and
"I would like to display the blank cells as ""yellow"" using the conditional format, but

"
Excel.Range=sheet.get_Range;
range.FormatConditions.Add (Excel.XlFormatConditionType.xlBlanksCondition);
range.Interior.ColorIndex=ExcelColorIndex.Yellow;

After running with the above code,
"Yellow" is not specified in a conditional format
However, the entire range has been repainted.

range.FormatConditions.Add (Excel.XlFormatConditionType.xlBlanksCondition).Interior.ColorIndex=27
with as in vba There was also an error using .

Could you tell me how to set the conditional format to "yellow"?

c# vba

2022-09-30 19:11

1 Answers

Excel.Range (whole range) is the code to repaint.
Re-paint Excel.FormatCondition
range.FormatConditions.Add returns Excel.FormatCondition and should work if you write it like the code below.

using System;
using Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApp1
{
    class program
    {

        static void Main (string[]args)
        {
            // Rewrite to ToDo destination file path
            string file=System.IO.Path.Combine(Environment.CurrentDirectory, "Book 1.xlsx");

            Excel.Application app=new Excel.Application();
            Excel.Workbookbook=app.Workbooks.Open(file);
            try
            {
                Excel.Worksheet sheet=book.Works[1];
                Excel.Range=sheet.Range ["A1", "B2" ];

                // Store conditional formatting in variables
                Excel.FormatCondition=range.FormatConditions.Add (Excel.XlFormatConditionType.xlBlanksCondition);
                // Specify the ColorIndex format
                condition.Interior.ColorIndex=27;

                book.Save();
            }
            finally
            {
                book.Close();
            }
        }
    }
}

Did you use with the code in the second half in vba?
The variable name is range and you may have unintended errors.
I ran the following code on vba and it worked.

Sub button 1_Click()
    Dimrng Asrange
    Set rng = range ("A1:B2")
    rng.FormatConditions.Add (Excel.XlFormatConditionType.xlBlanksCondition).Interior.ColorIndex=27
End Sub

If you change the rng variable to the range variable, the following error occurs:

Runtime Error '91':
Object or With block variable is not set.


2022-09-30 19:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.