VBA excel Target.Address =单元格范围
Posted
技术标签:
【中文标题】VBA excel Target.Address =单元格范围【英文标题】:VBA excel Target.Address = Range of Cells 【发布时间】:2017-02-21 12:38:29 【问题描述】:我有代码来做两件事:首先,它将位于工作表 2 中的数据验证下拉列表中的项目排序为“,”到工作表 1 中所需的单元格范围。此外,如果用户选择相同的项目,它会从选定的单元格中删除它。
代码的另一个选项是当用户选择下拉列表的单元格时(位于D2:F325
它应该放大 100% 以查看列表中的项目(因为它的字体大小太小了,看不见)
在下面的代码中几乎可以完美运行。因为,只有当我从所需范围中选择一个单元格时,它才会缩放:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Count > 1 Then GoTo exitHandler
If Target.Address = Range("XYZ").Address Then
ActiveWindow.Zoom = 100
[A5000] = "zoomed"
ElseIf [A5000] = "zoomed" Then
'Otherwise set the zoom to original
ActiveWindow.Zoom = 70
[A5000].ClearContents
End If
exitHandler:
Application.EnableEvents = True
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String
Dim strVal As String
Dim i As Long
Dim lCount As Long
Dim Ar As Variant
On Error Resume Next
Dim lType As Long
If Target.Count > 1 Then GoTo exitHandler
lType = Target.Validation.Type
If lType = 3 Then
Application.EnableEvents = False
newVal = Target.Value
Application.Undo
oldVal = Target.Value
Target.Value = newVal
If oldVal = "" Then
'do nothing
Else
If newVal = "" Then
'do nothing
Else
On Error Resume Next
Ar = Split(oldVal, ", ")
strVal = ""
For i = LBound(Ar) To UBound(Ar)
Debug.Print strVal
Debug.Print CStr(Ar(i))
If newVal = CStr(Ar(i)) Then
'do not include this item
strVal = strVal
lCount = 1
Else
strVal = strVal & CStr(Ar(i)) & ", "
End If
Next i
If lCount > 0 Then
Target.Value = Left(strVal, Len(strVal) - 2)
Else
Target.Value = strVal & newVal
End If
End If
End If
End If
exitHandler:
Application.EnableEvents = True
End Sub
XYZ
是单元格 D2
的名称,因为我尝试将此范围命名为使用此函数进行选择,但它不起作用。
最后,Target.Address
如何选择整个范围 D2:F325
【问题讨论】:
您的代码开头有这一行If Target.Count > 1 Then GoTo exitHandler
,如果您选择超过 1 个单元格,则退出您的 Sub
【参考方案1】:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Count > 1 Then GoTo exitHandler
If Not Application.Intersect(Target, Range("D2:F325")) Is Nothing Then
ActiveWindow.Zoom = 100
[A5000] = "zoomed"
ElseIf [A5000] = "zoomed" Then
'Otherwise set the zoom to original
ActiveWindow.Zoom = 70
[A5000].ClearContents
End If
exitHandler:
Application.EnableEvents = True
End Sub
效果很好。
【讨论】:
- 如果答案对您有用,您能否接受您的答案? (“社区”将其排在前面,因为它似乎未解决。)以上是关于VBA excel Target.Address =单元格范围的主要内容,如果未能解决你的问题,请参考以下文章
EXCEL VBA中单元格发生改变触发事件,怎么指定某个单元格