简体   繁体   English

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

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

I am working on the function Worksheet_Change and I have an issue. 我正在使用Worksheet_Change函数,但是有一个问题。 I cannot get a cell using the row and the column ID. 我无法使用行和列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 (就像您在代码前面所做的那样)。

Set myCell = .Cells(selectedRow, myColumn)

You should always declare all your variables too (and note Rory's point). 您还应该始终声明所有变量(并注意Rory的观点)。 The myColumn line looks somewhat redundant too. 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用VBA从特定的Excel单元格迭代到该列中具有值的最新行? - How can I iterate from a specific Excel cell to the latest row having a value in this column using VBA? 在VBA(Excel)中,列A如何插入ID标头,然后再插入1-X UNTIL,使其到达表示数据最高行的空单元格? - In VBA (Excel) how can Column A insert an ID header followed by 1-X UNTIL it reaches the empty cell representing the highest row with data? 在Excel(VBA)中按ID获取单元格值 - Get Cell value by ID in Excel (VBA) 无法使用Excel VBA将文本分配给单元格 - Can't assign text to cell with Excel VBA Excel VBA-从合并顶部单元格的列中获取顶部单元格 - Excel VBA - Get top cell from column where top cell is merged Excel VBA:如果列A中的单元格为空(长数据集),则删除整行 - Excel VBA: Delete entire row if cell in column A is blank (Long Dataset) 在MS Excel VBA中使用Row()和Column()在公式中计算单元格地址 - Calculating Cell Addresses in Formula with Row() and Column() in MS Excel VBA 如果在其他工作表的列中未找到单元格值,则Excel VBA删除行 - Excel VBA delete row if cell value not found in a column in other sheet 最后不是给定行中的空单元格(列); Excel VBA - Last not empty cell (column) in the given row; Excel VBA 在Excel VBA中循环浏览A列,从B列中获取一个随机单词,然后在C列中输出该行 - Loop through Column A in Excel VBA, get a random word from Column B and output the row in Column C
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM