问题
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