excel or excel VBA: how can I let user click on a cell and use it as a match result to an existing cell

寵の児 提交于 2020-01-07 03:06:25

问题


Wanted

Attached is a snip picture of what I want to do. I have one column that lists all the options, and on the second column some items. For each item I want the user to physically select a cell and I can then use that selection as the match to the item. For example if the use click on "user1" then I need to populate cell D4 with text "user1". How can I achieve this? Thanks!


回答1:


On the code for the worksheet from which you want to use the selection:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Target.Column = 1 Then
        Dim s As String
        s = Cells(Target.Row, Target.Column)
        Sheets("SHEETNAME").Range("D4") = s
    End If

End Sub



回答2:


You can use a worksheet event handler. Depending on your precise conditions, use either SelectionChange or DoubleClick.

For example, in the worksheet code module:

This code looks for a user to select a cell in column 1, then updates D4 with the selection's value.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Cells.Count = 1 Then
        If Target.Column = 1 Then
            Range("D4").Value = Target.Text
        End If
    End If
End Sub

Bear in mind that this will also update if the user selects a cell with the keyboard, which is why you may prefer using the before double click event:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

(You will also need to add Cancel = True to the above code if you use this, or it will allow the users to edit the value in that cell)

Hope this Helps!



来源:https://stackoverflow.com/questions/34009811/excel-or-excel-vba-how-can-i-let-user-click-on-a-cell-and-use-it-as-a-match-res

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!