excel - 需要自动用户名和时间的帮助
问题描述
我正在使用 Excel,我需要在其中获取两个条目的示例 1 的自动用户名和时间。如果我在第 2 列中插入一个值,我需要在单元格“A”和“O”2 处输入用户名和时间。在同一个 Excel 中再次为 Column(7) 中的条目工作表我需要在单元格“I”和“N”中的日期和用户名
我的代码适用于单点,我很困惑如何使用两次。
检查我尝试并建议的代码
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim rng As Range, c As Range
Set rng = Application.Intersect(Target, Me.Columns(2))
If rng Is Nothing Then Exit Sub
For Each c In rng.Cells
If Len(c.Value) > 0 Then
If Len(c.Offset(0, -1).Value) = 0 Then
With c.EntireRow
.Cells(1, "A").Value = Now()
'.Cells(1, "B").Value = Date
.Cells(1, "O").Value = Environ("username")
End With
End If
End If
Set rng = Application.Intersect(Target, Me.Columns(7))
If rng Is Nothing Then Exit Sub
For Each c In rng.Cells
If Len(c.Value) > 0 Then
If Len(c.Offset(0, -1).Value) = 0 Then
With c.EntireRow
.Cells(1, "I").Value = Now()
'.Cells(1, "B").Value = Date
.Cells(1, "N").Value = Environ("username")
End With
End If
End If
Next c
End Sub
解决方案
有问题的行是If rng Is Nothing Then Exit Sub
因为如果Target
不在第 2 列中,它会退出 sub 并且永远不会到达第 7 列的第二个测试。
所以If Not rng Is Nothing Then
改用:
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim rng As Range, c As Range
Set rng = Application.Intersect(Target, Me.Columns(2))
If Not rng Is Nothing Then
For Each c In rng.Cells
If Len(c.Value) > 0 Then
If Len(c.Offset(0, -1).Value) = 0 Then
With c.EntireRow
.Cells(1, "A").Value = Now()
'.Cells(1, "B").Value = Date
.Cells(1, "O").Value = Environ("username")
End With
End If
End If
Next c
End If
Set rng = Application.Intersect(Target, Me.Columns(7))
If Not rng Is Nothing Then
For Each c In rng.Cells
If Len(c.Value) > 0 Then
If Len(c.Offset(0, -1).Value) = 0 Then
With c.EntireRow
.Cells(1, "I").Value = Now()
'.Cells(1, "B").Value = Date
.Cells(1, "N").Value = Environ("username")
End With
End If
End If
Next c
End If
End Sub
推荐阅读
- numpy - Scikit-Learn PCA 或 Numpy Eigen 分解中的错误?
- css - 仅适用于下拉按钮的水平滚动
- selenium - 用硒开始镀铬
- android - 在drawables中的xml文件中出现未知错误
- c++ - C++中的“typedef”、“using”、“namespace”和“using namespace”有什么区别?
- analytics - 依赖项为名义时的线性回归
- spring-boot - 编写执行时间超过 5 分钟的方法的最佳方法是什么?
- javascript - Javascript 对象或数组
- postgresql - Postgres 触发器副作用与行级安全选择策略无序发生
- swift - textViewDidBeginEditing 快速在 2 个单独的 textViews 上