我编写了以下代码,为cola中具有大于0的值的单元格指定日期。在此代码中,我包含了一个传递当前日期的函数。这纯粹是出于学习目的。我以为我可以很容易地写出r.value.offset = now()。
但是,当我运行此代码时,它会抛出以下错误消息'对象的方法范围'全局失败。见下面的代码
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
答案 0 :(得分:1)
你所做的是“近乎完美”,只是一个小小的调整:
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
修改#1:强>
这是一个以特定格式返回当前日期/时间的函数,作为字符串
Function getdate() As String
getdate = Format(Now, "dd/mm/yyyy hh:mm")
End Function
另一种方法是让函数返回现在作为真正的Excel日期/时间并将格式应用于外部单元格
修改#2:强>
此版本保护以前输入的日期/时间:
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