Question

I have written the following code that assigns a date to a cell within col a that has a value greater than 0. Within this code I have include a function that passes the current date. This was included purely for a learning purpose. I have thought I could quite easily just write r.value.offset = now().

However when I run this code it throws the following error message 'method range of object' global failed. see code below

Sub gdate()

   Dim i As Long, r As Range, coltoSearch As String

    coltoSearch = "A"

    For i = 1 To Range(coltoSearch & Rows.Count).End(xlUp).Row
        Set r = Range(coltoSearch & i)
        If Len(r.Value) = 0 Then
            MsgBox "No Value, in " & r.Address
            ElseIf Len(r.Value) > 0 Then
            Range(r.Value).Offset = date1
        End If
    Next i

End Sub


Function getdate(ByRef date1 As Date)
Dim d As String
 d = Now()
 date1 = d
End Function
Was it helpful?

Solution

What you did was "nearly perfect", just a minor tweak:

Sub gdate()
    Dim i As Long, r As Range, coltoSearch As String
    coltoSearch = "A"
    For i = 1 To Range(coltoSearch & Rows.Count).End(xlUp).Row
        Set r = Range(coltoSearch & i)
        If Len(r.Value) = 0 Then
            MsgBox "No Value, in " & r.Address
        Else
            r.Offset(0, 1) = Date
        End If
    Next i
End Sub

EDIT#1:

Here is a function that returns the current date/time in a specific format as a String

Function getdate() As String
    getdate = Format(Now, "dd/mm/yyyy hh:mm")
End Function

an alternative is to have the function just return Now as a true Excel date/time and apply the formatting to the cell externally

EDIT#2:

This version protects a previously entered date/time:

Sub gdate()
    Dim i As Long, r As Range, coltoSearch As String
    coltoSearch = "A"
    For i = 1 To Range(coltoSearch & Rows.Count).End(xlUp).Row
        Set r = Range(coltoSearch & i)
        If Len(r.Value) = 0 Then
            MsgBox "No Value, in " & r.Address
        Else
            If r.Offset(0, 1) = "" Then
                r.Offset(0, 1) = Date
            End If
        End If
    Next i
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top