2016-09-20 28 views
2

我試圖創建一個小宏,該用戶在每次修改某行時都會在特定列中插入一個時間戳。首先,我創建了一個Function,它返回應該插入時間戳的列的索引。作爲第二步,我創建了一個子程序來監視變更。作爲後者的一部分,我使用行索引和列索引設置時間戳的目標範圍。當我使用Range.Cells()引用單個單元格時出現錯誤1004

This is what my data looks like

enter image description here

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

enter image description here

+2

刪除範圍包裝。只需使用Set TimestampCell = Cells(TimestampRow,TimestampColumn)' –

+1

爲什麼你需要使用'Range'? 'Range'函數已經返回一個範圍(包含一個單元格) – litelite

+0

刪除'Range'調用:'Set TimestampCell = Cells(TimestampRow,TimestampColumn)' – Rory

回答

1

你的行和列瓦爾由於某種原因字符串。他們應該是整數類型。

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 
+0

非常感謝@Jeeped!這解決了這個問題(以及我最近一兩個小時的頭痛......)。 –

+0

我已經將這兩個變量聲明爲字符串,因爲在開始時我嘗試調用'Range'(沒有'Cells'屬性),並且理解你必須使用字符串作爲'Range'的參數。我只是忘了更新變量類型... –

+0

是的,你將不得不將數字列號轉換爲一個字母(在StackOverflow上有很多例子),但使用[Range.Cells屬性](https:// msdn .microsoft.com/en-us/library/office/ff196273.aspx)應該更容易。 – Jeeped

相關問題