Excel,VBA无法从行ID和列ID获取单元格

时间:2018-01-02 13:51:09

标签: excel-vba vba excel

我正在处理Worksheet_Change函数,我遇到了问题。 我无法使用行和列ID获取单元格。

我尝试了很多解决方案,但没有。

你能帮我吗?

这是我的剧本:

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

在分配范围(对象)变量时,您需要使用Set(正如您之前在代码中所做的那样)。

Set myCell = .Cells(selectedRow, myColumn)

您应该始终声明所有变量(并注意Rory的观点)。 myColumn行也看起来有些多余。

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