当单元格具有特定值时如何插入用户名标记?

时间:2019-02-22 02:00:26

标签: excel vba

我正在尝试在单元格中填充特定值时插入用户名。

示例

如果用户将单元格X14设置为“完成”或“跳过”,那么我希望单元格Z14具有当前在工作簿中工作的用户名。而且当该单元格不再具有“完成”或“跳过”功能时,用户名也会消失。

你们中有人可以帮助我做到这一点吗?最好只使用excel公式,但VBA也不错。

谢谢!

2 个答案:

答案 0 :(得分:1)

如果要查找Column X Target.Column = 24 )上的任何单元格的更改,请使用以下内容...

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column = 24 And Target.Count = 1 Then
    If Target = "Done" Or Target = "Skip" Then
        Application.EnableEvents = False
            Target.Offset(0, 2) = Application.UserName
        Application.EnableEvents = True
    End If
End If

End Sub

答案 1 :(得分:0)

根据您的情况推断,您输入数据的用户可能不止一个,我认为,VBA方法是您应该采用的方法。

将此代码复制并粘贴到工作表模块中,然后自定义<<<自定义此>>>部分

Private Sub Worksheet_Change(ByVal Target As Range)

    ' Define object variables
    Dim statusRange As Range
    Dim changedCell As Range

    ' Define variables
    Dim currentUserName As String
    Dim userNameColumn As String
    Dim statusColumnNumber As Integer
    Dim statusValuesList As Variant

    ' <<< Customize this >>>
    Set statusRange = Range("X10:X100") ' Limit the cells that will record the status
    statusValuesList = Array("Done", "Skip") ' Add more status values separated by commas and inside quotes (this is not case-sensitive)
    userNameColumn = "Z" ' Column letter where the UserName is going to be stamped

    ' Prevent from firing other events while making changes to cells
    Application.EnableEvents = False

    ' Validate if cell changed belongs to valid column and rows and if it has a valid status
    If Not Intersect(Target, statusRange) Is Nothing Then

        For Each changedCell In Target

            If Not IsError(Application.Match(changedCell.Value, statusValuesList, 0)) Then

                ' Get current username
                currentUserName = Environ("Username")

            Else

                ' Empty username string
                currentUserName = vbNullString

            End If

            ' Assign username to cell in previously defined column and same row
            Range(userNameColumn & changedCell.Row).Value = currentUserName

        Next changedCell

    End If

    ' Reenable firing events
    Application.EnableEvents = True

End Sub