我有一个简单的表格,可以在一天的不同时间输入计数。
我的表单将表中最后一行的值加载到UserForm中,以便打开表单以输入下一个计数的人都可以将先前的值放置在表单中:
Private Sub UserForm_Initialize()
Dim lr As Long
lr = ActiveSheet.Range("A1").End(xlDown).Row
eightWkd.Value = Cells(lr, 3)
nineWkd.Value = Cells(lr, 4)
ten30Wkd.Value = Cells(lr, 6)
noonWkd.Value = Cells(lr, 8)
one30Wkd.Value = Cells(lr, 10)
threeWkd.Value = Cells(lr, 12)
four30Wkd.Value = Cells(lr, 14)
sixWkd.Value = Cells(lr, 15)
这是我的提交按钮代码,用于设置值。更改加载的值有效。我找到第一个空行
Private Sub SubmitButton_Click()
Dim ws As Worksheet
Set ws = Worksheets("daily_count")
Dim lr As Long, varDay As Long
With ws
lr = .Cells(.Rows.Count, varDay).End(xlUp).Offset(1, 0).Row
.Cells(lr, 1).Value = Me.DateWkd.Value
.Cells(lr, 2).Value = Me.DayWkd.Value
.Cells(lr, 3).Value = Me.eightWkd.Value
.Cells(lr, 4).Value = Me.nineWkd.Value
.Cells(lr, 6).Value = Me.ten30Wkd.Value
.Cells(lr, 8).Value = Me.noonWkd.Value
.Cells(lr, 10).Value = Me.one30Wkd.Value
.Cells(lr, 12).Value = Me.threeWkd.Value
.Cells(lr, 14).Value = Me.four30Wkd.Value
.Cells(lr, 15).Value = Me.sixWkd.Value
我尝试了以下逻辑,根据是否设置了日期值(A列)在现有的最后一行和新的行之间进行选择。
If ActiveSheet.Range("A1") = Format(Date, "mm/dd/yy") Then
r = ActiveSheet.Range("A1").End(xlDown).Row
Else
r = .Cells(.Rows.Count, varDay).End(xlUp).Offset(1, 0).Row
End If
那么,如何更新行中的单元格而不是创建新行?
答案 0 :(得分:0)
如何使用.Find方法查找具有当前日期的行,然后更新该行的值(如果找到),如果找不到,则将值添加到下一个空闲行:
Private Sub SubmitButton_Click()
Dim ws As Worksheet
Set ws = Worksheets("daily_count")
Dim lr As Long, varDay As Long, rng as Range
FindVal = Format(Date, "mm/dd/yy")
Set Rng = ws.Range("A:A").Find(What:=FindVal, lookat:=xlWhole)
If Not Rng Is Nothing Then
With ws
.Cells(Rng.Row, 1).Value = Me.DateWkd.Value
.Cells(Rng.Row, 2).Value = Me.DayWkd.Value
.Cells(Rng.Row, 3).Value = .Cells(Rng.Row, 3).Value + Me.eightWkd.Value
.Cells(Rng.Row, 4).Value = .Cells(Rng.Row, 4).Value + Me.nineWkd.Value
.Cells(Rng.Row, 6).Value = .Cells(Rng.Row, 6).Value + Me.ten30Wkd.Value
.Cells(Rng.Row, 8).Value = .Cells(Rng.Row, 8).Value + Me.noonWkd.Value
.Cells(Rng.Row, 10).Value = .Cells(Rng.Row, 10).Value + Me.one30Wkd.Value
.Cells(Rng.Row, 12).Value = .Cells(Rng.Row, 12).Value + Me.threeWkd.Value
.Cells(Rng.Row, 14).Value = .Cells(Rng.Row, 14).Value + Me.four30Wkd.Value
.Cells(Rng.Row, 15).Value = .Cells(Rng.Row, 15).Value + Me.sixWkd.Value
End With
Else
With ws
lr = .Cells(.Rows.Count, varDay).End(xlUp).Offset(1, 0).Row
.Cells(lr, 1).Value = Me.DateWkd.Value
.Cells(lr, 2).Value = Me.DayWkd.Value
.Cells(lr, 3).Value = Me.eightWkd.Value
.Cells(lr, 4).Value = Me.nineWkd.Value
.Cells(lr, 6).Value = Me.ten30Wkd.Value
.Cells(lr, 8).Value = Me.noonWkd.Value
.Cells(lr, 10).Value = Me.one30Wkd.Value
.Cells(lr, 12).Value = Me.threeWkd.Value
.Cells(lr, 14).Value = Me.four30Wkd.Value
.Cells(lr, 15).Value = Me.sixWkd.Value
End With
End If
End Sub