简体   繁体   English

excel或excel VBA:如何让用户单击某个单元格并将其用作与现有单元格的匹配结果

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

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". 例如,如果使用单击“ user1”,那么我需要用文本“ user1”填充单元格D4。 How can I achieve this? 我该如何实现? Thanks! 谢谢!

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

You can use a worksheet event handler. 您可以使用工作表事件处理程序。 Depending on your precise conditions, use either SelectionChange or DoubleClick. 根据您的确切条件,使用SelectionChange或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. 这段代码寻找用户选择第1列中的单元格,然后用选择的值更新D4。

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) (如果使用此代码,则还需要在上面的代码中添加Cancel = True,否则它将允许用户编辑该单元格中的值)

Hope this Helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM