gpt4 book ai didi

excel - 如何搜索多个工作表?

转载 作者:行者123 更新时间:2023-12-04 20:28:42 31 4
gpt4 key购买 nike

我在 Worksheet2 中搜索任何文本并在 ListBox1 中显示结果。

Private Sub SearchButton_Click()

'ListBox1.Clear
ListBox1.RowSource = ""
ListBox1.ColumnHeads = False

'listbox column headers
Me.ListBox1.AddItem
For A = 1 To 8
Me.ListBox1.List(0, A - 1) = Sheet2.Cells(1, A)
Next A
Me.ListBox1.Selected(0) = True

'Populating listbox from search
Dim i As Long

For i = 2 To Sheet2.Range("A100000").End(xlUp).Offset(1, 0).Row
For j = 1 To 8
H = Application.WorksheetFunction.CountIf(Sheet2.Range("A" & i, "H" & i), Sheet2.Cells(i, j))
If H = 1 And LCase(Sheet2.Cells(i, j)) = LCase(Me.TextBox2) Or H = 1 And _
Sheet2.Cells(i, j) = Val(Me.TextBox2) Then
Me.ListBox1.AddItem
For X = 1 To 8
Me.ListBox1.List(ListBox1.ListCount - 1, X - 1) = Sheet2.Cells(i, X)
Next X
End If
Next j
Next i

End Sub

我想搜索多个工作表,但不知道如何在不完全更改代码的情况下实现这一目标。

最佳答案

您将不得不更改对 Sheet2 的引用。如果你想看多张纸。没有办法解决这个问题。但是,它将使您的代码更加灵活。从这样做开始:

Private Sub SearchButton_Click()

'ListBox1.Clear
ListBox1.RowSource = ""
ListBox1.ColumnHeads = False

'listbox column headers
Me.ListBox1.AddItem
For A = 1 To 8
Me.ListBox1.List(0, A - 1) = Sheet2.Cells(1, A)
Next A
Me.ListBox1.Selected(0) = True

Dim ws As Worksheet 'This is the new line of code where you define your worksheet
Set ws = ActiveWorkbook.Sheet2 'Replace all references below to Sheet2 with this

'Populating listbox from search
Dim i As Long

For i = 2 To ws.Range("A100000").End(xlUp).Offset(1, 0).Row
For j = 1 To 8
H = Application.WorksheetFunction.CountIf(ws.Range("A" & i, "H" & i), Sheet2.Cells(i, j))
If H = 1 And LCase(Sheet2.Cells(i, j)) = LCase(Me.TextBox2) Or H = 1 And _
ws.Cells(i, j) = Val(Me.TextBox2) Then
Me.ListBox1.AddItem
For X = 1 To 8
Me.ListBox1.List(ListBox1.ListCount - 1, X - 1) = Sheet2.Cells(i, X)
Next X
End If
Next j
Next i
End Sub

现在您已经概括了您的 Sub,您可以修改 ws 的值。尽可能多地重复代码。如果它是您工作簿中的每个工作表,您可以使用 For Each循环,比如
For Each ws In ActiveWorkbook
'All your code for the ws here
Next ws

或者,您可以预先在数组中定义工作表。
Dim SheetList(0 to 2) As String
Dim k As Integer

SheetList(0) = "Sheet 2 Name"
SheetList(1) = "Sheet 4 Name"
SheetList(2) = "Sheet 3 Name"
SheetList(3) = "Sheet 6 Name"

For k = LBound(SheetList) To UBound(SheetList)
ws = ActiveWorkbook.Sheets(SheetList(k))
'The rest of your code from above
Next k

您没有在问题中指定什么样的表格有多少,或者它们是如何组织的。但是,这些选项应该足以让您到达您想要去的地方。

关于excel - 如何搜索多个工作表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53922554/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com