【问题标题】:Error 1004 when I use Range.Cells() to reference a single cell当我使用 Range.Cells() 引用单个单元格时出现错误 1004
【发布时间】: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 的问题,但我没有找到任何解决方案的线索(如果我没有正确搜索,请告诉我)。

This is what the Debugger says

【问题讨论】:

  • 移除 Range 包装器。只需使用Set TimestampCell = Cells(TimestampRow, TimestampColumn)
  • 为什么需要使用RangeCells 函数已经返回一个范围(包含单个单元格)
  • 删除Range调用:Set TimestampCell = Cells(TimestampRow, TimestampColumn)
  • 请注意,如果 getTimestampColumn 找不到匹配项,即使进行了更正,您也会得到 1004。
  • 它是如何工作的?您在函数中重新使用保留字 Range.Column 属性,而不将其声明为 Long 整数。使用dim col as long,然后使用For col= 1 To 5getTimestampColumn = col。添加Exit For 以在找到循环时中断循环。您正在有效地渲染 Option Explicit 无用。

标签: vba excel


【解决方案1】:

由于某种原因,您的行和列变量是字符串。它们应该是 Long 整数类型。

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

【讨论】:

  • 非常感谢@Jeeped!这解决了这个问题(以及我过去一两个小时的头痛......)。
  • 我已经将这两个变量声明为字符串,因为一开始我尝试调用Range(没有Cells 属性)并且理解您必须使用字符串作为Range 的参数。我只是忘了更新变量类型...
  • 是的,您必须将数字列号转换为字母(StackOverflow 上有很多示例),但使用 Range.Cells property 应该更容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
  • 2020-02-24
  • 2015-07-06
相关资源
最近更新 更多