我作業的公司最近從 Office 2016 遷移到 M365。我們的一些啟用宏的電子表格使用括號運算式作為 Application.Evaluate 方法的快捷方式。例如:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim msg As String
On Error GoTo ErrHandler:
If Target.Columns.Count > 100 Then
Dim row As Range
For Each row In Target.Rows
RemoveRowBorders row:=row.row, firstColumn:=[colSourceDevice], lastColumn:=[colItemNumber]
Next
UpdateItemNumbers startingRow:=[rowStart], maxRange:=[maxRange]
GoTo My_Exit
End If
If Target.Column >= [colSourceDevice] And Target.Column <= [colItemNumber] Then
SetCalculations cellRange:=Target
End If
My_Exit:
Exit Sub
ErrHandler:
msg = "An error occurred on cell auto-update: " & vbNewLine & Err.Description
MsgBox msg
Resume My_Exit
End Sub
“colSourceDevice”是一個命名范圍/物件,它參考一個回傳列號的公式,括號內的運算式是呼叫 Application.Evaluate 方法的快捷方式。“colSourceDevice”中提到的公式是:
=VALUE(COLUMN('HS - Main'!$A$2))
在 Excel 2016 中,括號內的運算式回傳列號(變體/雙精度)。
在 M365 Excel 中,括號內的運算式回傳一個陣列 (Variant/Variant),其中包含一項 (Variant/Double)。
在 M365 Excel 中,這會導致型別不匹配錯誤。
我可以使用物件模型方法而不是括號運算式并獲得預期結果:
Application.Evaluate("colSourceDevice")(1) 'returns column number (Variant/Double)
Why does the square bracketed expression return a different data type in M365 vs Excel 2016?
EDIT:
As chris neilsen alluded to, there was a major change to the Excel calculation engine in 2018.
See here:

這表現出您描述的行為

它實際做的是回傳一個包含 1 個元素的動態陣列。
要將該值作為 Variant 回傳,請通過將其包裝在其中來修改命名范圍 INDEX
colSourceDevice2 Refers to = =INDEX(COLUMN(),1,1)

結果就是你想要的

免責宣告:
綜上所述,這是針對一些構思不良的代碼的創可貼修復。我的建議:重構您的代碼以消除這種和其他不良做法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/348386.html
標籤:excel vba named-ranges
上一篇:帶格式的文本連接
