2017-02-21 876 views
0

我有一個代碼可以做2件事:首先它將來自數據驗證刪除列表的項目排列在圖2中,並用「,」表示位於表單中的單元格的所需範圍同樣,如果用戶選擇相同的項目,它將從選定的單元格中刪除它。VBA excel Target.Address =單元格範圍

代碼的另一種選擇是,當用戶選擇下拉列表中的單元格時(位於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.Adress如何選擇全範圍D2:F325

在此先感謝

+0

你在代碼開始時有這行 - 如果Target.Count> 1 Then GoTo exitHandler',如果你選擇多於1個單元格,你退出你的'Sub' –

回答

0
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 

它工作得很好。

相關問題