Excel VBA 动态数组的预编译测试

Excel VBA Precompile Test For Dynamic Array

开始掌握 Excel VBA 编程技能,尝试在旧的 32 位和 64 位 Windows 10 上共享代码,并在 [=] 上模拟 Office 365 Windows 21=]:其中一个平台无法识别最近动态数组添加的“{ }”(多单元格数组)和“@”(隐式交集运算符),而另一个平台无法识别“Cells.Replace”命令与 Formula2 构造,但我对具有唯一标识符的变量(其中标准查找函数失败)使用“间接”和“&”(连接),但 Excel 将它们视为数组。一个平台需要 Formula2(Mac 跳过指令),另一个甚至不使用它编译(完全停止),没有它宏代码崩溃(Mac 必须“读取”公式在 sheet 上检索值,而不是从声明的变量中检索值,因为它的沙箱问题)。我正在尝试进行预编译查询以绕过所示的错误测试,但它失败了。关于停止 Excel 自动添加花括号“{}”或符号“@”的预编译测试的建议?

#If IsError(Cells.Replace What:=WhatNow, Replacement:=Whatzit, LookAt:=xlPart, FormulaVersion:=xlReplaceFormula2) Then

因为 'xlReplaceFormula2' 必须包含在某些 Mac 环境中,但会被较旧的编译器踢出,所以 Formula2 结构必须放在预编译 (#) if 语句中。但是,新公式的测试不会在预编译模式下执行,因为它会产生类型不匹配错误。这是我找到的解决方法:

a) 测试较新的公式以确定环境是否创建动态数组特殊字符({ }、@),以及 b) 在预编译语句中执行替换命令。

这可以替换额外的字符,因此它不会干扰旧平台中的公式操作,在旧平台中使用自定义连接 (&) 组合来代替数据透视表或基本的查找公式。

    Dim WhatNow, Whatzit

   'Define special character
    WhatNow = "@"  'eg, "{", "}"
   'Define formula to edit
    Whatzit = "Cells"  'eg, "If", "Indirect", etc.

   'Test for formula that contains dynamic array
    If Application.Evaluate("=XLOOKUP(1,{1,2,3},{3,2,1})") Then
       'Include 'xlReplaceFormula2' within a precompile (#) 'If' statement
        #If Not Err = 0 Then
         Cells.Replace What:=WhatNow, Replacement:=Whatzit, LookAt:=xlPart, _
             SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
             ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
        #Else
        'Else, older platform - use older formula construct
         Cells.Replace What:=WhatNow, Replacement:=Whatzit, LookAt:=xlPart, _
             SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
             ReplaceFormat:=False
        #End If
    End If