vba - VBA 的 Worksheet_Change 函数使用 Intersect 方法与 Cells 作为范围定义器
问题描述
当相关单元格之一已更改时,我正在尝试使我的电子表格自动填充相应的单元格。我之前刚刚将目标定义为:
If Target.Address = "$A$5" then
并且没有问题。但是,现在我的目标可以是许多单元格之一,并且我读到 intersect 方法应该能够为此工作,但是当我输入我的代码时:
If Intersect(Target, Range(Cells(12,2), Cells(12,j-1))) Is Nothing Then
(我正在尝试更改目标下方的单元格,目标是 12B 和 12(j-1) 之间的任何单元格,其中 j 是先前定义的)我收到以下错误:“运行时错误'1004':应用程序定义或对象定义的错误”但是据我所知,我的代码与周围的所有示例完全相同。
我的完整代码是(尽管我的 vlookup 也可能存在不相关的错误)
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range(Cells(12, 2), Cells(12, j-1))) Is Nothing Then
If IsEmpty(Target) Then
Target.Interior.ColorIndex = 19
Else:
If Range("$A$13").Value = "" Then
Range("$A$13").Value = "Care Type"
Range("$A$13").Font.Bold = True
End If
Target.Interior.ColorIndex = xlNone
Target.Offset(1, 0).Interior.ColorIndex = 19
Target.Offset(2, 0).Value = Application.WorksheetFunction. _
VLookup(Target, Sheets("Sheet2").Range("$E$3:$F$6"), 2)
Target.Offset(2, 0).Font.Bold = True
i = 2
Do Until IsEmpty(Cells(11, i))
If Cells(11, i).Value <= ChildCount Then
Cells(12, i).Interior.ColorIndex = 19
End If
i = i + 1
Loop
End If
End If
End Sub
解决方案
在使用 Intersect 确定您的范围内至少有一个单元格已更改后,您需要遍历匹配的单元格。
关闭事件处理,否则当您开始更改工作表上的值时,Worksheet_Change 将自行运行。
Private Sub Worksheet_Change(ByVal Target As Range)
If not Intersect(Target, Range(Cells(12, 2), Cells(12, 11))) Is Nothing Then
on error goto safe_exit
application.enableevents = false
dim t as range
for each t in Intersect(Target, Range(Cells(12, 2), Cells(12, 11)))
If IsEmpty(t) Then
t.Interior.ColorIndex = 19
Else
If Range("$A$13").Value = "" Then
Range("$A$13").Value = "Care Type"
Range("$A$13").Font.Bold = True
End If
t.Interior.ColorIndex = xlNone
t.Offset(1, 0).Interior.ColorIndex = 19
t.Offset(2, 0).Value = Application.WorksheetFunction. _
VLookup(Target, Sheets("Sheet2").Range("$E$3:$F$6"), 2)
t.Offset(2, 0).Font.Bold = True
i = 2
'I really don't know what the following code is intended to do
'probably better as a conditional formatting rule
Do Until IsEmpty(Cells(11, i))
If Cells(11, i).Value <= ChildCount Then
Cells(12, i).Interior.ColorIndex = 19
End If
i = i + 1
Loop
End If
next t
End If
safe_exit:
application.enableevents = true
End Sub
推荐阅读
- php - 如何根据数量(高-低)php排列3,4和5个值
- reactjs - 反应钩子 setState 落后一步
- powerbi - Power BI:DAX:以固定开始日期运行 Sum - 即使在过滤时
- javascript - 未捕获的 ReferenceError:在 d3.js 中加载 .csv 文件时未定义数据
- java - 使用 gson gradle 从 JSON 中读取键和值
- c# - 使用 HttpCompletionOption.ResponseHeadersRead 的 HttpClient 超时
- android - 谷歌地图活动(没有得到纬度,语言)
- python - 在使用 PIP 命令安装任何内容期间,pip 配置了需要 TLS/SSL 的位置
- android - 使用 Drive API 创建一个 txt 文件
- sql - 根据 select 语句中的条件创建列