Excel:获取单元格颜色

时间:2011-02-24 21:55:10

标签: excel

1)如何使用Excel宏获取单元格的颜色?我无法使用此功能:

Sub BGCol(MRow As Integer, MCol As Integer)  
bgColor = Cells(MRow, MCol).Interior.ColorIndex  
End Sub

2)在单元格x中,我想要具有以下公式:

=BGCol(x,4)

那么如何获取当前行索引?

3 个答案:

答案 0 :(得分:8)

Function GetColor(Mycell As Range)

    GetColor = Mycell.Interior.ColorIndex

End Function

:::使用公式:: = GETCOLOR(X4)

答案 1 :(得分:6)

您应该使用功能:

Function BGCol(MRow As Integer, MCol As Integer)  As Integer
   BGCol = Cells(MRow, MCol).Interior.ColorIndex  
End Function

答案 2 :(得分:0)

或者,如果您不想使用宏或VBA,则可以使用 Aspose.Cells API获得单元格颜色

单元格颜色单元格填充颜色

表示
  • Cell> Style> ForegroundColor

单元格字体颜色

表示
  • Cell> Style> Font>颜色

代码内使用的Excel文件示例

请考虑快照中显示的以下示例Excel文件。在此处,单元格 C4 黄色颜色填充,其字体颜色为红色

enter image description here


C# Java 中的以下代码将加载示例Excel文件,如上所示,并访问单元格C4及其样式对象。然后,它会打印单元格填充颜色(即黄色)和单元格字体颜色(即红色)。

还请参见下面给出的控制台输出,并阅读代码中的评论以获取更多信息。

C#

// Directory path for input Excel file.
string dirPath = "D:/Download/";

// Load the input Excel file inside workbook object.
Aspose.Cells.Workbook wb = new Workbook(dirPath + "SampleExcelColor.xlsx");

// Access first worksheet.
Worksheet ws = wb.Worksheets[0];

// Access cell C4 by name.
Cell cell = ws.Cells["C4"];

// Access cell style.
Style st = cell.GetStyle();

// Print fill color of the cell i.e. Yellow.
// Please note, Yellow is (R=255, G=255, B=0)
Console.WriteLine(st.ForegroundColor);

// Print font color of the cell i.e. Red.
// Please note, Red is (R=255, G=0, B=0)
Console.WriteLine(st.Font.Color);

控制台输出-C#

Color [A=255, R=255, G=255, B=0]
Color [A=255, R=255, G=0, B=0]

Java

// Directory path for input Excel file.
String dirPath = "D:/Download/";

// Load the input Excel file inside workbook object.
com.aspose.cells.Workbook wb = new Workbook(dirPath + "SampleExcelColor.xlsx");

// Access first worksheet.
Worksheet ws = wb.getWorksheets().get(0);

// Access cell C4 by name.
Cell cell = ws.getCells().get("C4");

// Access cell style.
Style st = cell.getStyle();

// Print fill color of the cell i.e. Yellow.
// Please note, Yellow is (R=255, G=255, B=0)
System.out.println(st.getForegroundColor());

// Print font color of the cell i.e. Red.
// Please note, Red is (R=255, G=0, B=0)
System.out.println(st.getFont().getColor());

控制台输出-Java

com.aspose.cells.Color@ffffff00
com.aspose.cells.Color@ffff0000