我刚刚发布了这个代码昨天与一个不同的问题,这简单地解决了(谢谢!)。我正在尝试使用宏来搜索某个字符串的Excel文档。我想获取找到字符串的单元格的地址,并将它们一个接一个地放在当前工作表的第i列中。我的问题是宏只识别字符串的第一次出现,并不识别其他实例,即使我知道它们存在。我的代码如下。搜索一个字符串“datatoFind”超出第一个出现
Option Explicit
Sub Find_Data()
Dim datatoFind As String
Dim rangeSearch As Range
Dim rangeLast As Range
Dim foundRange As Range
Dim strFirstAddress As String
Dim sheetCount As Integer
Dim sheetCounter As Integer
Dim currentSheet As Integer
Dim foundmatrixCounter As Integer
foundmatrixCounter = 2 'initialize this to the second row so the total can be placed in the first row when done
'set search range
Set rangeSearch = ActiveSheet.Range("B2:X100")
'set last cell in range
Set rangeLast = rangeSearch.Cells(rangeSearch.Cells.Count)
currentSheet = ActiveSheet.Index
datatoFind = InputBox("Please enter the value to search for")
If datatoFind = "" Then Exit Sub
sheetCount = ActiveWorkbook.Sheets.Count
For sheetCounter = 1 To sheetCount
Sheets(sheetCounter).Activate
Set foundRange = Cells.Find(What:=datatoFind, After:=Cells(1, 1), LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
'if datatoFind is found in search range
If Not foundRange Is Nothing Then
'save the address of the first occurrence of datatoFind, in the strFirstAddress variable
strFirstAddress = foundRange.Address
Do
'Find next occurrence of datatoFind
Set foundRange = foundRange.FindNext(foundRange)
'Place the address of this occurrence in the next cell down in the column that holds found values (i column)
Cells(foundmatrixCounter, 9).Value = foundRange.Address
'Increment the loop counter for the i column
foundmatrixCounter = foundmatrixCounter + 1
'The Loop ends on reaching the first occurrence of datatoFind
Loop Until foundRange.Address = strFirstAddress
End If
Cells(1, 9).Value = foundmatrixCounter 'Put the total number of instances, in this case foundmatrixCounter, in Z1
Next sheetCounter
If foundRange Is Nothing Then
MsgBox ("Value not found")
Sheets(currentSheet).Activate
End If
End Sub
可能还有一些其他的错误,我对VBA相当陌生。任何帮助将非常感激。
那么对于初学者你以后'如果datatoFind =“”然后退出Sub'线... – Chrismas007 2014-12-03 15:10:42
为什么一个else语句缺少必要的'Else'?如果If语句是假的,那么它将被跳过,是正确的?为了清楚起见,或者如果我有一个If Else声明,我只会对其他声明发表正确的看法。 – 2014-12-03 16:06:48
http://www.techonthenet.com/excel/formulas/if_then.php – Chrismas007 2014-12-03 16:10:07