【发布时间】:2016-09-20 13:57:44
【问题描述】:
我正在尝试创建一个小宏,当用户修改行时,它会在特定列中插入时间戳。首先,我创建了一个函数,它返回应插入时间戳的列的索引。作为第二步,我创建了一个子程序来监控更改。作为后者的一部分,我通过使用行索引和列索引来设置时间戳的目标范围。
This is what my data looks like
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
我的问题:宏引发运行时错误 (1004)。当我将范围硬编码到特定单元格时,它工作正常。因此,似乎我以错误的方式使用 Range(Cells()) 。我已经阅读了 Cells 属性的帮助条目和几个解释如何使用它的网站,但我不知道我做错了什么。
我知道有很多关于如何使用 Range(Cells()) 和错误 1004 的问题,但我没有找到任何解决方案的线索(如果我没有正确搜索,请告诉我)。
【问题讨论】:
-
移除 Range 包装器。只需使用
Set TimestampCell = Cells(TimestampRow, TimestampColumn) -
为什么需要使用
Range?Cells函数已经返回一个范围(包含单个单元格) -
删除
Range调用:Set TimestampCell = Cells(TimestampRow, TimestampColumn) -
请注意,如果
getTimestampColumn找不到匹配项,即使进行了更正,您也会得到 1004。 -
它是如何工作的?您在函数中重新使用保留字 Range.Column 属性,而不将其声明为 Long 整数。使用
dim col as long,然后使用For col= 1 To 5和getTimestampColumn = col。添加Exit For以在找到循环时中断循环。您正在有效地渲染Option Explicit无用。