简体   繁体   中英

Excel, VBA, can't get cell from row and column ID

I am working on the function Worksheet_Change and I have an issue. I cannot get a cell using the row and the column ID.

I have tried a lot of solutions but nothing.

Could you help me please?

This is my script:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range
Dim myCell As Range

Set KeyCells = Range("G4:N19")

If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then

    selectedRow = Target.Row
    myColumn = Range("F" & 1).Column

    With Sheets(1)
        ' selectedRow = 16, myColumn = 6
        myCell = .Cells(selectedRow, myColumn)
        ' myCell is empty
        MsgBox myCell

    End With

End If
End Sub

Thank you for your help.

You need to use Set when assigning a range (object) variable (as you did earlier in the code).

Set myCell = .Cells(selectedRow, myColumn)

You should always declare all your variables too (and note Rory's point). The myColumn line looks somewhat redundant too.

Private Sub Worksheet_Change(ByVal Target As Range)

Dim KeyCells As Range
Dim myCell As Range
Dim selectedRow As Long
Dim myColumn As Long

Set KeyCells = Range("G4:N19")

If Not Application.Intersect(KeyCells, Target) Is Nothing Then
    selectedRow = Target.Row
    myColumn = Range("F1").Column
    With Sheets(1)
        ' selectedRow = 16, myColumn = 6
        Set myCell = .Cells(selectedRow, myColumn)
        ' myCell is empty
        MsgBox myCell.Value
    End With
End If

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM