Excel VBA - 在单击单击时搜索另一个工作表

时间:2015-05-28 17:23:12

标签: excel vba excel-vba

我正在寻找一种方法来获取excel来搜索Sheet2中单击Sheet1的单元格中的相同文本。

例如: Sheet2包含名称(列A),地址(列B)和城市(列c),而Sheet1包含相同名称的列表(以及各种其他信息)。为简单起见,我需要的是能够单击Sheet1上的名称并让它返回Sheet2上相同名称的行号。在消息框中显示信息就足够了。

关于如何让这个工作的任何想法?我很难找到从哪里开始。

1 个答案:

答案 0 :(得分:0)

将此代码放在Sheet1(Sheet1)中:

Sheet1

假设您的工作表名称是Sheet1和Sheet2:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

'If you select more than one cell, ignore
If Target.CountLarge > 1 Then Exit Sub

'If you select a blank cell, ignore
If Target.Value = vbNullString Then Exit Sub

Dim Finder, ClickRange

'We want the event to fire if you click in column A anywhere
Set ClickRange = Sheets("Sheet1").Range("A:A")

'If you click somewhere else, ignore
If Intersect(Target, ClickRange) Is Nothing Then Exit Sub

'Look for the value in sheet 2 column A
Set Finder = Sheets("Sheet2").Range("A:A").Find(Target.Value, LookAt:=xlWhole)

'If we don't find it, Exit Sub
If Finder Is Nothing Then Exit Sub

'To display the row:
MsgBox (Finder.Row)

'To Select it:
'If we find it, select sheet 2 and select the cell
'Sheets("Sheet2").Activate
'Finder.Select

End Sub
相关问题