尝试插入日期时的运行时错误“1004”

时间:2012-07-09 15:27:55

标签: excel excel-vba vba

我有这个脚本,我一直收到错误:Run-time error '1004': Method 'Range' of object _'Worksheet' failed

这是脚本:

Option Explicit
    Sub ONJL()

    Dim lastrow As Long
    Dim wsRD As Worksheet 'Raw Data

    Set wsRD = Sheets("Raw Data")

        With wsRD
            Application.ScreenUpdating = False
            lastrow = wsRD.Range("J:J").End(xlUp).Offset(1, 0)
            wsRD.Range("J" & lastrow).Value = "=Today()"
        End With

    End Sub

我认为这就是你要查找最后一行的方法,然后将今天的日期粘贴到最后一个单元格上?

2 个答案:

答案 0 :(得分:2)

有几个问题:

  • 当您使用with时,需要使用.
  • 引用该对象
  • Offset(x,y)的结果是范围,而不是数字 - 您对该行感兴趣,因此您需要添加.Row
  • End(xlUp) thingy必须从最后一行开始工作

这可能就是你的意思:

Sub ONJL()

    Dim lastrow As Long
    Dim wsRD As Worksheet 'Raw Data

    Set wsRD = Sheets("Raw Data")

    With wsRD
        Application.ScreenUpdating = False
        lastrow = .Range("J" & .Rows.Count).End(xlUp).Row
        .Range("J" & lastrow + 1).Formula = "=Today()"
    End With

End Sub

并且不要忘记在某个地方转动画面更新。

答案 1 :(得分:2)

lastrow被声明为Long变量,但Offset返回Range个对象。 Row属性为您提供行的数值。

Sub ONJL()

  Dim lastrow As Long
  Dim wsRD As Worksheet  'Raw Data

  Set wsRD = Sheets("Raw Data")

  With wsRD
    Application.ScreenUpdating = False
    lastrow = .Cells(Rows.Count, 10).End(xlUp).Offset(1, 0).Row
    .Range("J" & lastrow).Formula = "=Today()"
  End With

Application.ScreenUpdating = True

End Sub