excel - Excel事件VBA相交中的范围替代

标签 excel vba

在确定特定数组以在其中实现函数的情况下,我知道如何创建该代码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
 If Not Intersect(Target, Range("A1:O7000")) Is Nothing Then
  MsgBox "Hi"
 End If
End Sub
所以相交仅当我在 Argument2 中写入时,此处才有效范围 功能。
我不想确定整个数组。当我想通过这种形状开发这段代码时:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
 Dim SafeTbl As ListObject
  Set SafeTbl = ListObjects("Safe")
   If Not Intersect(Target, SafeTbl.Range.Address) Is Nothing Then
    MsgBox "Hi"
   End If
End Sub
我发现这个 Type mismatch编译错误:
Type Mismatch Error
我不知道为什么会出现这个错误。虽然我看到我的开发与以前的代码一样。 由于此代码确定只有数组有数据。

最佳答案

正如评论中所建议的,.Address是一个字符串。 Intersect 方法需要范围作为参数,而不是您当前提供的范围地址的文本。Type mismatch编译错误告诉您“变量或属性的类型不正确”(https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/type-mismatch-error-13)
微软说:

[Application.Intersect method (Excel)] Returns a Range object that represents the rectangular intersection of two or more ranges.


明确地说,这意味着您的代码需要更改为:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
 Dim SafeTbl As ListObject
  Set SafeTbl = ListObjects("Safe")
   If Not Intersect(Target, SafeTbl.Range) Is Nothing Then
    MsgBox "Hi"
   End If
End Sub
可以在此处阅读有关 Intersect 方法的更多信息:https://docs.microsoft.com/en-us/office/vba/api/excel.application.intersect
还有更多关于 Range 属性的信息:https://docs.microsoft.com/en-us/office/vba/api/excel.range.range
更新
正如@BigBen 正确指出的那样,在您的情况下,我们实际上指的是 ListObject.Range属性(property),因此有关此的更多信息在这里:https://docs.microsoft.com/en-us/office/vba/api/excel.listobject.range

关于excel - Excel事件VBA相交中的范围替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68226790/

相关文章:

excel - 从右键菜单中删除临时选项

excel - 清除组合框的选择

excel - 自动化错误 -2147221080 (800401a8)

Excel 类型提供程序有错误 - 它需要程序集 "Excel.dll"

excel - VBA 隐藏宏

vba - 重新运行代码时出错

excel - 如何将 Excel 标签标题中的文本垂直居中?

excel - 创建空列表,然后将元素附加到该列表

CreateObject ("InternetExplorer.Application"中的 VBA 自动化错误)

excel - EnterKey 在 VBA 用户窗体中按下按钮