VBA在所有工作表中搜索双击单元格值

标签 vba excel events

前几天我学会了如何使用VBA双击sheet1中的单元格,然后它会跳转到Sheet 2中具有相同值的单元格。

我现在有一个类似的报告,只不过这次我需要双击 Sheet1 中的单元格,然后在同一工作簿中的每个工作表中搜索该值。

我的第一个可行方案的代码在这里: 在本工作簿中:

Private Sub Workbook_SheetBeforeDoubleClick _
(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)

If Len(Target.Value) = 0 Then Exit Sub

'If the double-clicked cell isn't in column A, we exit.
If Target.Column <> 1 Then Exit Sub

'Calls the procedure FindName in Module1 and passes the cell content
Module1.FindName Target.Value

End Sub

在模块 1 中:

Sub FindName(ByVal sName As String)
'Finds and activates the first cell
'with the same content as the double-clicked cell. sName
'is the passed cell content.
Dim rColumn As Range
Dim rFind As Range

'Activate the sheet Contact Data.
Worksheets("All Data").Activate

'Set the range rColumn = column B
Set rColumn = Columns("B:B")

'Search column B
Set rFind = rColumn.Find(sName)

'If found the cell is activated.
If Not rFind Is Nothing Then
   rFind.Activate
Else
   'If not found activate cell A1
   Range("A1").Activate
End If

Set rColumn = Nothing
Set rFind = Nothing

End Sub

如果有人知道如何在其中创建一个工作表循环,以便它在每个工作表中查找值,我将非常感激!

谢谢! 艾米丽 我之前代码的来源:http://www.sitestory.dk/excel_vba/hyperlinks-alternative.htm

最佳答案

给你。将搜索所有工作表,如果没有找到则返回消息。如果找到,将激活单元格。

Sub FindName(ByVal sName As String)

    'Finds and activates the first cell in any sheet (moving left-to-right)
    'with the same content as the double-clicked cell. sName
    'is the passed cell content.
    Dim rFind As Range
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets

        Set rFind = ws.Columns(2).Find(sName, lookat:=xlWhole) ' look for entire match, set to xlPart to search part of cell ... 2 is column B.

        If Not rFind Is Nothing Then
            Dim bFound As Boolean
            bFound = True
            ws.Activate
            rFind.Select
            Exit For
        End If

    Next

    If Not bFound Then MsgBox sName & " not found in any sheet."

End Sub

关于VBA在所有工作表中搜索双击单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35002910/

相关文章:

vba - 格式化(动态)

excel - ReDim Preserve 停止在 Excel VBA 代码中工作

javascript - 在javascript中将数组附加到事件?

c# - Fluent NHibernate - 如果其依赖项之一不存在,则不返回实体

Excel VBA计算方法不更新数组公式;显示为#N/A

vba - workbooks.open 拉错文件

excel - 寻找在单元格上使用 "Find"的替代方案

ruby-on-rails - AXLSX:为 rspec 测试解析 xlsx 文件

python - 在 openpyxl 生成的 XLSX 文件中正确呈现新行

javascript - 可以在不改变布局或 DOM 的情况下使用 jQuery Mobile 吗?