尝试为UDF返回PChar或OleVariant时编译错误

这个标题并不完全说明问题的实质。

我有一个UDF函数返回一个PChar。

function AccountDescription(sAccountId: PChar) : PChar; stdcall; 

这工作正常,但我意识到如果accountId没有find我想返回#N / A。

我发现了CVErr(xlErrNA),并将签名更改为返回OleVariant。 但是现在我收到[Error]不兼容的types:'OleVariant'和'PAnsiChar'。

我找不到任何有关如何解决这个问题的信息,所以我认为我对这个问题的理解是不正确的。

我试着只是传递一个string编译,但产生了“无效变体types”的运行时错误。

完整的代码是:

 function AccountDescription(sAccountId: PChar): OleVariant; stdcall; var strResult: string; strPChar : PChar; begin try strResult:= repo.GetAccount(sAccountId).Description; strPChar := strAlloc(length(strResult)+1) ; StrPCopy(strPChar, strResult) ; Result := strPChar; except Result := CVErr(xlErrNA); end; end; 

注意:是excel负责销毁string还是我的清理? 我应该创build一个副本,或者我应该只是返回一个指向现有string的指针。 input后,我觉得我应该返回一个指针。

更新:在示例中删除了一些不相关的代码。

现在使用:

 function AccountDescription(sAccountId: PChar): OleVariant; stdcall; var strResult: string; begin try Result := PChar(repo.GetAccount(sAccountId).Description); except Result := CVErr(xlErrNA); end; end; 

你不需要PChar ,你可以直接给一个OleVariant分配一个String (它将被RTL转换成一个BSTR ,接收者在使用它的时候会自由的)。

 Result := repo.GetAccount(sAccountId).Description; 

至于报告错误,你的Delphi代码中是否有一个可行的CVErr()函数? 在VB中, CVErr()返回一个包含错误代码( xlErrNA是2042)的Varianttypes的Error (Delphi中的xlErrNA )。 Delphi有一个VarAsError()函数用于同样的目的:

 Result := VarAsError(2042);