【发布时间】:2015-06-03 13:35:11
【问题描述】:
通过其自动化界面使用 Excel 的一个烦人的事情是弱输入。
返回值可以包含 anything 不同的类型。
如何测试caller返回的变体是否是ExcelRange接口?
function TAddInModule.InBank: boolean;
var
ExcelAppAsVariant: OleVariant;
test: string;
Caller: OleVariant;
begin //Exception handling omitted for brevity.
Result:= false;
ExcelAppAsVariant:= ExcelApp.Application;
Caller:= ExcelApp.Application.Caller[EmptyParam, 0];
if IDispatch(Caller) is ExcelRange then begin //E2015 Operator not applicable
Result:= lowercase(Caller.Parent.Name) = 'bank'
end;
end;
(很奇怪,as 运算符可以正常工作,(IDispatch(Caller) as ExcelRange).Parent; 编译得很好)。
以下代码有效,但似乎过于冗长:
if VarIsType(Caller, varDispatch) then begin
IUnknown(Caller).QueryInterface(ExcelRange, ICaller)
if Assigned(ICaller) then ICaller......
也没有内置函数VarIsInterface(Variant, Interface)。
如何测试 OleVariant 是否包含给定接口?
另请参阅:How to cast OleVariant to IDispatch derived?
编辑
谢谢大家,我使用以下方法进行测试,因为 Excel 混合了接口和 OleStrings 作为可能的返回值。
if VarIsType(Caller, varDispatch) and Supports(Caller, ExcelRange) then begin
【问题讨论】:
-
接口一直支持
as进行类型转换。奇怪的是is不起作用,而不是as起作用。
标签: delphi variant office-automation