我試圖創建一個小宏,該用戶在每次修改某行時都會在特定列中插入一個時間戳。首先,我創建了一個Function,它返回應該插入時間戳的列的索引。作爲第二步,我創建了一個子程序來監視變更。作爲後者的一部分,我使用行索引和列索引設置時間戳的目標範圍。當我使用Range.Cells()引用單個單元格時出現錯誤1004
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())和Error 1004的問題,但我還沒有找到任何解決方案的線索(讓我知道如果我沒有正確搜索)。
This is what the Debugger says
刪除範圍包裝。只需使用Set TimestampCell = Cells(TimestampRow,TimestampColumn)' –
爲什麼你需要使用'Range'? 'Range'函數已經返回一個範圍(包含一個單元格) – litelite
刪除'Range'調用:'Set TimestampCell = Cells(TimestampRow,TimestampColumn)' – Rory