通过其自动化界面使用Excel的一个令人烦恼的事情是弱类型. 返回值可以包含任何不同类型. 如何测试调用者返回的变量是否为ExcelRange接口? function TAddInModule.InBank: boolean;var ExcelAppAsVar
返回值可以包含任何不同类型.
如何测试调用者返回的变量是否为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)作为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我可能会使用
Supports:
if Supports(Caller, ExcelRange) then ....
这解析为@Stijn给出的相同代码,但Supports调用更简洁.
