错误1004时,我使用Range.Cells()引用单个单元格

我试图创build一个小的macros,只要用户修改一行,就在特定的列中插入一个时间戳。 首先,我创build了一个函数,它返回应该插入时间戳的列的索引。 作为第二步,我创build了一个子程序来监视变化。 作为后者的一部分,我使用行索引和列索引来设置时间戳的目标范围。

这是我的数据看起来像

在这里输入图像说明

Dim Timestamp As Date Dim TimestampCell As Range Dim TimestampColumn As String Dim TimestampRow As String Dim Column As Integer Function getTimestampColumn() As Integer For Column = 1 To 5 If Cells(1, Column).value = "Last updated on" Then getTimestampColumn = Column End If Next Column End Function Sub Worksheet_Change(ByVal Target As Range) If Target.Row > 1 Then TimestampColumn = getTimestampColumn() TimestampRow = Target.Row Timestamp = Now Set TimestampCell = Range(Cells(TimestampRow, TimestampColumn)) TimestampCell = Timestamp End If End Sub 

我的问题:macros抛出运行时错误(1004)。 当我将范围硬编码到特定单元格时,它工作正常。 所以,好像我正在使用Range(Cells())的方式是错误的。 我已阅读Cells属性的帮助条目和几个网站,解释如何使用它,但我无法弄清楚我做错了什么。

我知道有很多关于如何使用Range(Cells())和Error 1004的问题,但我还没有find任何解决scheme的线索(让我知道如果我没有正确search)。

这是debugging器说的

在这里输入图像说明

你的行和列variables是由于某种原因的string。 它们应该是整数types。

 Option Explicit Dim Timestamp As Date Dim TimestampCell As Range Dim TimestampColumn As Long '<~~ Long integer Dim TimestampRow As Long '<~~ Long integer Dim Column As Integer Function getTimestampColumn() As Integer Dim col As Long For col = 1 To 5 If Cells(1, col).Value = "Last updated on" Then getTimestampColumn = col Exit For End If Next col If col > 5 Then MsgBox "'Last updated on' not found" End Function Sub Worksheet_Change(ByVal Target As Range) If Target.Row > 1 Then TimestampColumn = getTimestampColumn() TimestampRow = Target.Row Timestamp = Now Set TimestampCell = Cells(TimestampRow, TimestampColumn) TimestampCell = Timestamp End If End Sub