在每个打开的工作表中搜索字符串

时间:2013-08-26 21:14:36

标签: vba

我想使用字符串FindString的每个实例中的值来填充UserForm1中的文本框。

我每个文本框都会获得唯一的WorkSheet。但是当我运行模块时,剩下的值来自工作表。

这意味着字符串Rng没有循环遍历WorkSheets,而是保留在最初的WorkSheet中。我该如何解决这个问题?

Public Sub FindString()
Dim FindString As Variant
Dim Rng As Range
Dim SheetName As String
Dim ws As Worksheet
Dim i As Integer

Application.ScreenUpdating = False
SheetName = ActiveSheet.Name

FindString = Cells(ActiveCell.Row, 1).Value

FindString = InputBox("Enter the case number to search for:", "Case ID", FindString)
If FindString = "" Then Exit Sub
If FindString = False Then Exit Sub


i = 1

For Each ws In Worksheets
    If ws.Name Like "Lang*" Then
        With ws

            If Trim(FindString) <> "" Then
                With Range("A:A")
                    Set Rng = .Find(What:=FindString, _
                                    After:=.Cells(.Cells.Count), _
                                    LookIn:=xlValues, _
                                    LookAt:=xlWhole, _
                                    SearchOrder:=xlByRows, _
                                    SearchDirection:=xlNext, _
                                    MatchCase:=False)
                    If Not Rng Is Nothing Then

            UserForm1.Controls("TextBox" & i) = ws.Name & vbTab & _
            Rng.Offset(0, 2).Value & vbTab & _
            Rng.Offset(0, 5).Value & vbTab & _
            Rng.Offset(0, 6).Value & vbTab & _
            Rng.Offset(0, 7).Value & vbTab & _
            Rng.Offset(0, 8).Value

            i = i + 1

                    Else: GoTo NotFound
                    End If
                End With
            End If

        End With
    End If
Next ws

Sheets(SheetName).Activate
Application.ScreenUpdating = True
UserForm1.Show

Exit Sub

NotFound:
Sheets(SheetName).Activate
Application.ScreenUpdating = True
MsgBox "Case ID not found"
Exit Sub

End Sub

1 个答案:

答案 0 :(得分:0)

知道了!

只需要添加

ws.Activate

If ws.Name Like "Lang*" Then