首先,我对VBA还是很陌生,并且对编码有非常基本的了解。另外,在问这个问题之前,我已经进行了研究,并尝试了几种不同的方法,因为我很自豪地承认我大部分时间都无法解决问题。但是,这让我很困惑,我再也无法花时间在上面了。
我正在使用由其他人创建和管理的工作簿。它非常无组织,每张纸中有数千行。我最初想创建一种可以更有效地使用此工作簿的方式。现在,我的老板希望我也使它适用于我部门的其他所有人。这就增加了一种显示每个实例位置的方法的需要。
我正在用手机编写所有这些内容,因为我的公司将所有内容都锁定了,如果我尝试发布正在处理的任何内容,我肯定会被解雇。
我希望它从提示中输入内容,进行搜索,然后尽可能以“表名,地址”的形式列出它的每个实例。
这是我编写的原始代码,目的只是为了使某些功能能够快速满足我的需求。我怀疑我将来可以使用还是应该使用其中的任何一个,但这可以很好地说明我正在使用的工具。我使用If函数浏览每个页面,因为我知道我可以使它正常工作,并且大部分都是白痴证明。
Sub Searcher
Dim Sh As Worksheet
Dim Prompt As String
Dim RetValue As String
Dim Rng As Range
Dim RowCrnt As Long
Do While True
RetValue = InputBox(Prompt & “Enter info to search for”)
If RetValue = “” Then
Exit Do
End If
With Worksheets(“Sheet1”).Activate
Set Rng = Cells.Find(RetValue)
If Not Rng Is Nothing Then
RowCrnt = Rng.Row
Rng.Activate
Prompt = “I found this info in Sheet1 in row “”” & RowCrnt & “”””
Else
With Worksheets(“Sheet2”).Activate
‘ Same thing again for each sheet in the workbook
Else
Prompt = “This information does not exist in this workbook”
End With
End If
End With
Prompt = Prompt & vbLf
Loop
End Sub
答案 0 :(得分:0)
尝试在单独的Sub中循环遍历每个工作表,然后调用“ Searcher” Sub,将每个工作表作为参数传递。
Sub ForEachWorksheet()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Call Searcher(ws)
Next
End Sub
Sub Searcher(WsToSearch)
Dim Sh As Worksheet
Dim Prompt As String
Dim RetValue As String
Dim Rng As Range
Dim RowCrnt As Long
Set Sh = WsToSearch
Do While True
RetValue = InputBox(Prompt & “Enter info to search for”)
If RetValue = “” Then
Exit Do
End If
With Sheets(Sh)
Set Rng = Cells.Find(RetValue)
If Not Rng Is Nothing Then
RowCrnt = Rng.Row
Rng.Activate
Prompt = “I found this info in Sheet1 in row “”” & RowCrnt & “”””
Else
With Worksheets(“Sheet2”).Activate
‘ Same thing again for each sheet in the workbook
Else
Prompt = “This information does not exist in this workbook”
End With
End If
End With
Prompt = Prompt & vbLf
Loop
End Sub
答案 1 :(得分:0)
我假设您不想在每张纸上进行不同的搜索。以下内容使您可以在所有工作表中执行1次搜索,并输出MsgBox
以告知您所找到的内容。
Sub Searcher()
Dim Sh As Worksheet
Dim Prompt As String
Dim RetValue As String
Dim Rng As Range
Dim RowCrnt As Long
RetValue = InputBox(Prompt & "Enter info to search for")
If RetValue = "" Then
Exit Sub
End If
For Each Sh In ActiveWorkbook.Worksheets
Set Rng = Sh.Cells.Find(RetValue)
If Not Rng Is Nothing Then
RowCrnt = Rng.Row
Prompt = Prompt & "I found this info in " & sh.Name & " in row """ & RowCrnt & """" & vbLf
End If
Next
If Prompt = "" Then Prompt = "Nothing found"
MsgBox Prompt
End Sub