前几天我学会了如何使用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/