Vba excel if target address

 

seggi

Пользователь

Сообщений: 350
Регистрация: 05.03.2020

#1

21.04.2021 09:51:32

Пишу простенький скрипт, где на клик в определенных ячейках срабатывает назначение переменной.

Код
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim ha As Integer
    If Target.Address = "$A$1" Then
    ha = 1
    ElseIf Target.Address = "$A$2" Then
    ha = 2
    ElseIf Target.Address = "$A$3" Then
    ha = 3
    ElseIf Target.Address <> "$A$1" Or Target.Address <> "$A$2" Or Target.Address <> "$A$3" Then
    '
    End If
If ha = 0 Then
'
ElseIf ha > 0 Then
MsgBox ha

Else
End Sub

Идея такая. Пользователь кликает в ячейки A1, A2, A3 и соответственно в программу передаются значения 1,2,3
Пока проверяю значение MsgBox
Но при клике в другие ячейки идет все равно какая-то обработка. Как указать в программе то, что нужно игнорировать любые клики вне области A1:A3?

Goedenavond!

 

МатросНаЗебре

Пользователь

Сообщений: 5516
Регистрация: 05.02.2014

#2

21.04.2021 10:05:49

Код
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Not Intersect(Target, Range("A1:A3")) Is Nothing Then
        Dim ha As Integer
        Select Case Target.Address(0, 0)
        Case "A1": ha = 1
        Case "A2": ha = 2
        Case "A3": ha = 3
        Case Else
        End Select
        
        If ha = 0 Then
        ElseIf ha > 0 Then
            MsgBox ha
        Else
        End If
    End If
End Sub
 

seggi

Пользователь

Сообщений: 350
Регистрация: 05.03.2020

МатросНаЗебре, Спасибо большое

 

RAN

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

#4

21.04.2021 11:30:11

Цитата
seggi написал:
Как указать в программе то, что нужно игнорировать любые клики вне области A1:A3?

Не писать лишнего  :D

Код
ElseIf Target.Address <> "$A$1" Or Target.Address <> "$A$2" Or Target.Address <> "$A$3" Then
 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#5

21.04.2021 11:34:41

Код
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Not Intersect(Target, Range("A1:A3")) Is Nothing Then
        Select Case Target.Address(0, 0)
        Case "A1": MsgBox 1
        Case "A2": MsgBox 2
        Case "A3": MsgBox 3
        End Select
    End If
End Sub
 

Ігор Гончаренко

Пользователь

Сообщений: 13746
Регистрация: 01.01.1970

#6

21.04.2021 12:17:29

Код
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  If Intersect(Target, Range("A1:A3")) Is Nothing Then Exit Sub
  If Target.Count > 1 then Exit Sub
  ha = Target.Row
End Sub

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

seggi

Пользователь

Сообщений: 350
Регистрация: 05.03.2020

#7

21.04.2021 12:52:11

Цитата
RAN написал:
Не писать лишнего

Первые шаги, пытался велосипед изобрести.  :oops:

Goedenavond!

Return to VBA Code Examples

This article will demonstrate the use of VBA Target.Address.

vba target address selection change event

Target.Address

Target is the given name of the Range object variable that is contained in the argument of Worksheet Object Events, such as Worksheet_SelectionChange.

This event is triggered when you move from one cell to another in your worksheet.

To create a Worksheet Event, on the VBE Editor, select the appropriate worksheet and then, in the Object drop down box, select Worksheet.

vba target address worksheet

Consider the following code:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  If Target.Address = "$F$2" Then
    Range(Target.Address).Font.Bold = True
  End If
End Sub

Whenever you move your cursor this event will run and the IF Statement will test if the selected cell is F2. If it is, the cell will be set to Bold.

NOTE: The Target.Address is an absolute ($F$2), so when checking to see if you are on the appropriate cell, you must use $ signs in your string (“$F$2”).

The Target Range (and therefore the Target.Address method) is also avaialable with the Worksheet_Change; Worksheet_BeforeDoubleClick and Worksheet_BeforeRightClick event procedures in your Worksheet object.

Hi I am currently making a multiple list validation, but currently I am only able to make it to one cell E2 and I wish to make it in a range to go from E2:E40. I was thinking something along $E$2:$E$40. However, this does not work.

Private Sub Worksheet_Change(ByVal Target As Range)
' To allow multiple selections in a Drop Down List in Excel (without repetition)
Dim Oldvalue As String
Dim Newvalue As String
Application.EnableEvents = True
On Error GoTo Exitsub
If Target.Address = "$E$2" Then
  If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
    GoTo Exitsub
  Else: If Target.Value = "" Then GoTo Exitsub Else
    Application.EnableEvents = False
    Newvalue = Target.Value
    Application.Undo
    Oldvalue = Target.Value
      If Oldvalue = "" Then
        Target.Value = Newvalue
      Else
        If InStr(1, Oldvalue, Newvalue) = 0 Then
            Target.Value = Oldvalue & ", " & Newvalue
      Else:
        Target.Value = Oldvalue
      End If
    End If
  End If
End If
Application.EnableEvents = True
Exitsub:
Application.EnableEvents = True
End Sub

Pᴇʜ's user avatar

Pᴇʜ

56k9 gold badges49 silver badges73 bronze badges

asked Jun 9, 2021 at 8:20

kamsteg's user avatar

1

Use something like this

Dim AffectedCells As Range
Set AffectedCells = Intersect(Me.Range("E2:E40"), Target)

If Not AffectedCells Is Nothing Then
    ' do your stuff here …
End If

AffectedCells contains all cells within E2:E40 that were actually changed.

Make sure you loop through AffectedCells to handle each cell

Dim Cell As Range
For Each Cell In AffectedCells.Cells
    ' do your stuff with each Cell here …
Next Cell

answered Jun 9, 2021 at 8:23

Pᴇʜ's user avatar

PᴇʜPᴇʜ

56k9 gold badges49 silver badges73 bronze badges

Use this pattern for the intersections and consider building on it:

Private Sub Worksheet_Change(ByVal Target As Range)
        
    Dim intersectRange As Range
    Set intersectRange = Target.Parent.Range("E2:E40")
    
    If Not Intersect(Target, intersectRange) Is Nothing Then
        Debug.Print "Intersected " & Target.Address
    Else
        Debug.Print "Not intersected " & Target.Address
    End If
        
End Sub

answered Jun 9, 2021 at 8:26

Vityata's user avatar

VityataVityata

42.4k8 gold badges55 silver badges98 bronze badges

2

Sub макрос()

        Dim Target As Range
    Dim addresses(1 To 2) As Range
    Dim i As Long

            ‘1. Записываем в переменную «Taget» какую-нибудь ячейку, чтобы протестировать макрос.
    Set Target = Range(«A5»)

        ‘2. Запись диапазонов в массив «addresses».
    Set addresses(1) = Range(«A1:A4»)
    Set addresses(2) = Range(«A6:A9»)

        ‘3. Проверка, входит ли Target в какой-либо заданный диапазон.
    For i = 1 To UBound(addresses)
        If Not Intersect(Target, addresses(i)) Is Nothing Then
            Exit For
        End If
    Next i
    ‘ Если не было преждевременного выхода из цикла, значит Target не входит ни в один диапазон.
    If i > UBound(addresses) Then
        MsgBox «Не входит в диапазоны.», vbExclamation
        Exit Sub
    End If

        ‘4. Если макрос оказался здесь, значит Target входит в какой-то диапазон.

End Sub

[свернуть]

  • #4

Hi Shamas!

The address property simply identifies the location of the Target. Note that Target may be more than 1 cell.
You can use it to isolate a cell for macro execution. Example

Code:

If Target.Address  = "$A$1" Then

or

Code:

If Target.Addres <> "$A$1" Then Exit Sub

You can use this property in a messagebox

Code:

MsgBox "Value of " & Target.Address & " is " & Target.Value

Note that Target.Address is ALWAYS an absolute reference and in Caps.

So Target.Address =»A1″ or Target.Address = «$a$1» will not work

lenze

Edit: Vog’s code should go in the WorkSheet module, not the ThisWorkBook module

Last edited: Mar 21, 2008

Like this post? Please share to your friends:
  • Vba excel if sheet protected
  • Vba excel if row hidden
  • Vba excel if not isnumeric
  • Vba excel if not is nothing then
  • Vba excel if not exists