excel - Delphi 7 with..do 语句不适用于变体变量

标签 excel delphi with-statement

我正在通过 Delphi 7 使用 Microsoft Excel。它工作正常,但是在格式化行和范围时,我必须编写这么长的字符串。

XLApp.Workbooks[1].WorkSheets[NameDoc].Range['A19:L19'].Font.Bold := true;

所以我想摆脱艰苦的工作,并通过像这样的“with..do”语句来做到这一点
with XLApp.Workbooks[1].WorkSheets[NameDoc] do
begin
  Range['A19:L19'].Font.Bold := true;
end;

但是在编译阶段我看到了这个错误
Record, object or class type required

在字符串上 - “with..do”。

我以这种方式创建 Excel 对象
XLApp: Variant;
XLApp := CreateOleObject('Excel.Application');

我认为 with..do 语句不适用于变体类型变量,但我想知道我是否正确?如果我是对的,是否有任何解决方法可以让它发挥作用?

最佳答案

变体可以是任何东西,也可以什么都不是——编译器不知道也不知道:它就是所谓的“动态类型值”。因为它不知道——它不知道是否会有任何成员(属性、方法)以及是否有——它们会有什么名字。

获得强大的编译时类型的好处 - 包括使用 with但不仅 - 你必须使用接口(interface)变量,那些由 TExcelApplication 组件和具有这些值“静态类型化”的底层单元提供的接口(interface)变量 - 从而使 Delphi 编译器在编译时在运行之前知道值类型。该单元中有很多类型,如 iWorsksheet、iRange 和其他类型。

  • Borland Delphi 7 TExcelApplication.Connect works on office machines but not at client
  • http://www.delphipages.com/forum/showthread.php?t=157889
  • http://delphikingdom.ru/asp/viewitem.asp?catalogid=1270

  • 但是,由于这是关于引用计数和生命周期,我建议您明确使用临时变量,而不是使用 with。和隐含的不可见变量。由于您无法控制它们的生命周期和间隙,因此您以后可能会在某个意想不到的地方碰壁。我做到了。
    var tmpR: iRange; // assuming we have statically-typed API
    // for example - providing we using ExcelXP or Excel2000 unit
    
    tmpR := XLApp.Workbooks[1].WorkSheets[NameDoc];
    
    tmpR.Range['A19:L19'].Font.Bold := true; // instead of with
    
    with tmpR do // also possible but gives little benefit now
    begin        //    when we made a dedicated temp var
      Range['A19:L19'].Font.Bold := true;
    end;
    
    tmpR := nil; // crucial unless the most short and simplistic functions
    // just release hold on Excel's object - let it manage its memory freely,
    // by letting Excel know your program no more uses that object.
    

    另请阅读
  • https://en.wikipedia.org/wiki/Automatic_Reference_Counting
  • https://en.wikipedia.org/wiki/Component_Object_Model
  • 关于excel - Delphi 7 with..do 语句不适用于变体变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31044688/

    相关文章:

    excel - 外推线性回归

    vba - Excel 2010 : more frequent external data refresh with vba?

    delphi - 直接打印FastReport

    delphi - Delphi:泛型和TObjectList

    delphi - TIdSMTP : How to fix the error SSL negotiation Failed

    sql-server - 在单个表中使用 while 循环进行多个选择查询?是否可以?

    c# - 我如何从 vsto 插件中以编程方式加载自动化插件 (dll)

    Python - 带可选对象的with语句

    delphi - Delphi "with"关键字是一个不好的做法吗?

    excel - VBA运行时错误 '380' : A script engine for the specified language can not be created