在Excel工作簿中search特定的string

所以,我需要在VBA中创build一个Excelmacros来search一个string,然后将其与我select的预设string进行比较,然后在另一个工作表中更改单元格的值。

它是这样的:

Sub Macro1() Dim A As Integer Dim WS As Worksheet Dim ToCompare, Coniburo As String Coniburo = "My String" For Each WS In Worksheets For A = 1 To Rows.Count ToCompare = Left(Cells(A, 3), 100) If InStr(ToCompare, Coniburo) > 0 Then Sheets("Last Sheet").Cells(21, 2).Value = "233" End If Next A Next 

macros的作品…….如果我删除第一个For(search表单),只要我在一个“我的string”的工作表存在。 否则,它不起作用。 由于有17张纸,处理时间很长。

为什么不工作? 我在这里阅读了很多post,微软开发者论坛,一个名为Tech on the Net的网站,还有一些我错过了,但是我不知道为什么。

有人能指出我的方向吗?

使用With … End With将每个循环迭代的父级工作表集中在一起。

 Option Explicit Sub Macro1() Dim a As Long, Coniburo As String, ws As Worksheet Coniburo = "My String" For Each ws In Worksheets With ws For a = 1 To .Cells(.Rows.Count, "C").End(xlUp).Row If CBool(InStr(Left(.Cells(a, 3), 100), Coniburo, vbTextCompare)) Then Worksheets("Last Sheet").Cells(21, 2).Value = 233 End If Next a End With Next End Sub 

当在With … End With块中时,您需要以.Rows....Range(...).Cells(...)为周期前缀行,范围和单元格的调用。 这用With With End With描述的父工作表来标识它们。

我也使用vbTextCompare进行了大小写不敏感的比较。

在同一个工作表中,还有一个写入和重写233到同一单元格的问题,但这是另一回事。

我已经将这些规则放在了这里,但是我想展示如何使用内置的FIND函数来显着加快速度。 简单地说,我们将只处理C列中的每张表格; 我们将使用FIND函数来查找列C中包含searchstring的行号….然后,我们将仔细检查该单元格,以查看您的searchstring是否在您的要求的前100个字符之内。 如果是这样,我们会考虑一场比赛。 除了将“233”logging到“最后一页”表格之外,我还包括一些明亮的绿色突出显示,以帮助查看正在发生的事情。

 Sub findConiburo() Coniburo = "My String" For Each ws In Worksheets With ws.Range("C:C") myName = ws.Name 'useful for debugging queue = 1 'will be used to queue the FIND function x = 0 'loop counter Do 'loop to find multiple results per sheet On Error Resume Next 'Disable error handling 'FIND Coniburo within ws column C, log row number: 'Note ".Cells(queue, 1)" is a relative reference to the current WS, column C foundRow = .Find(What:=Coniburo, After:=.Cells(queue, 1), LookIn:=xlFormulas, LookAt _ :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Row 'If no result found then an error number is stored. Perform error handling: If Err.Number <> 0 Then 'No results found, don't do anything, exit DO to skip to next sheet: Exit Do End If On Error GoTo 0 'Re-enable error handling If x = 0 Then 'first loop - log the first row result: originalFoundRow = foundRow ElseIf foundRow = originalFoundRow Then 'Not the first loop. Same result as original loop = we're back at the start, so exit loop: Exit Do End If 'Update queue so next loop will search AFTER the previous result: queue = foundRow 'check if the string is not only SOMEWHERE in the cell, 'but specifically within the first 100 characters: ToCompare = Left(.Cells(foundRow, 1), 100) If InStr(ToCompare, Coniburo) > 0 Then .Cells(foundRow, 1).Interior.ColorIndex = 4 'highlight green Sheets("Last Sheet").Cells(21, 2).Value = "233" End If 'Update loop counter: x = x + 1 Loop End With Next ws End Sub