Delphi和Excel.FormatConditions

4

我正在使用Delphi XE2和Excel 2010进行早期绑定,设置条件格式时遇到了问题。

我想要复制的宏如下:

Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, _
    Formula1:="=6"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .ThemeColor = xlThemeColorAccent6
    .TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False

尽管我已经努力尝试,但我似乎无法访问相当于 Selction.FormatConditions(1) 的内容来运行。

我已经编写了以下代码,最接近所需的功能:

XR := Xlapp.Range(...) 
XR.FormatConditions.Delete;
XR.FormatConditions.Add(xlCellValue, xlGreater, '=6', EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam);

哪种方法有效。但是在我尝试定义颜色时遇到了问题。

FC := XR.FormatConditions[1];
FC.SetFirstPriority;
with FC.Interior do
begin
   PatternColorIndex := xlAutomatic;
   ThemeColor := xlThemeColorAccent6;
end;

然而,这个告诉我XR.FormatConditions(1)是IDispatch类型,因此与FormatCondition分配不兼容。我做错了什么?

你能清晰地表明错误在哪吗?是运行时错误还是编译时错误?哪一行出错了?精确的错误信息是什么?请使用复制/粘贴将错误信息提供给我们。选择错误信息文本,然后按下CTRL和C键。这将把它复制到剪贴板中。然后编辑问题并按下CTRL和V键。这将把其粘贴到问题中。 - David Heffernan
1个回答

5

您需要将 Selection 作为 ExcelRange 使用。对于 Excel XP,还需要将第二个和第三个参数设置为 OleVariant,因此这应该可以工作(无论如何都可以编译):

var
  Sel: ExcelRange;
  Op, Formula: OleVariant;
  Condition: FormatCondition;
begin
  Sel := ExcelApplication1.Selection[1] as ExcelRange;
  Op := xlGreater;
  Formula := '=6';
  Sel.FormatConditions.Add(xlCellValue, Op, Formula, EmptyParam);
  Condition := Sel.FormatConditions[1] as FormatCondition;
  Condition.Interior.PatternColorIndex := xlAutomatic;
  // Do whatever else
end;

XR是一个ExcelRange。.Add编译通过了,接下来的几行可能存在问题。 - Dan Kelly
1
我认为你可以从as ExcelRange的示例中推断出来。我又添加了一个Sel.FormatConditions[0] as FormatCondition;的示例。这是相同的概念 - 通过在IDispatch上使用as运算符检索所需的实际接口。 - Ken White
我在你的例子中错过了 "as"。强制转换做了我需要的事情。 - Dan Kelly
1
只是为了澄清,丹:这不是“强制转换”。这是从IDispatch请求实际接口的正确方式 - Delphi允许使用该语法,但编译器实际上在幕后使用QueryInterface来请求所需的接口,如果不可用,则不会返回任何接口。这不像类型转换。 :-) - Ken White
我不得不使用Sel.FormatConditions [1]作为索引不是基于零的。 - sav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接