search三个名字的工作表

而不是查找大于6的数字并将其发送到另一张纸上。 我想查找3个名字,这样我就可以search一个联系人列表,并将他们的信息从表单中提取到报表。

下面是我的旧代码:

Private Sub CommandButton1_Click() Dim ws As Worksheet, myCounter Dim erow, myValue As Long For Each ws In Sheets If ws.Range("C3").Value > 6 Then myCounter = 1 ws.Select ws.Range("c3").Select myValue = ws.Range("C3").Value Worksheets("Report").Select erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row ActiveSheet.Cells(erow, 1) = myValue nextValue = MsgBox("Value found in " & ws.Name & Chr(10) & "Continue?", vbInformation + vbYesvbNo, ws.Name & " C3 = " & ws.Range("C3").Value) Select Case nextValue Case Is = vbYes Case Is = vbNo Exit Sub End Select End If Next ws If myCounter = 0 Then MsgBox "None of the sheets contains a " & Chr(10) & "value greater than 6 in cell C3 ", vbInformation, "Not Found" End If End Sub 

我认为第三行应该是String而不是Long

我正在寻找的名字是“大卫”“安德烈”和“卡罗琳”,不知道我写了三次或使用循环。 此外,我不知道如何在整个电子表格中search这些名称。

下面的代码将在所有工作表中的单元格“C3”中查找名称“David”,“Andrea”和“Caroline”。 对于每一个匹配,它将它复制到“报告”工作表的列A中的第一个空行。

注意 :不需要使用SelectActiveSheet ,而是使用完全限定的CellsWorksheets

 Option Explicit Private Sub CommandButton1_Click() Dim ws As Worksheet, myCounter As Long Dim erow As Long, myValue As Long Dim nextValue As Long For Each ws In ThisWorkbook.Sheets With ws Select Case .Range("C3").Value Case "David", "Andrea", "Caroline" myCounter = 1 ' raise flag >> found in at least 1 sheet ' get first empty row in "Report" sheet erow = Worksheets("Report").Cells(Worksheets("Report").Rows.Count, 1).End(xlUp).Offset(1, 0).Row Worksheets("Report").Cells(erow, 1) = .Range("C3").Value nextValue = MsgBox("Value found in " & .Name & Chr(10) & "Continue?", vbInformation + vbYesNo, .Name & " C3 = " & .Range("C3").Value) Select Case nextValue Case Is = vbYes ' <-- if you are not doing anything here, you don't need it >> maybe you don't need the entire `Select Case` here Case Is = vbNo Exit Sub End Select End Select ' Select Case .Range("C3").Value End With Next ws If myCounter = 0 Then MsgBox "None of the sheets contains the names " & Chr(10) & " 'David', 'Andrea', 'Caroline' in cell C3 ", vbInformation, "Not Found" End If End Sub 

评论 :在下面的Select Case中, Case Is = vbYes似乎没有做任何事情:

 nextValue = MsgBox("Value found in " & .Name & Chr(10) & "Continue?", vbInformation + vbYesNo, .Name & " C3 = " & .Range("C3").Value) Select Case nextValue Case Is = vbYes ' <-- if you are not doing anything here, you don't need it >> maybe you don't need the entire `Select Case` here Case Is = vbNo Exit Sub End Select 

您可以用以下方法replace整个事物:

 If MsgBox("Value found in " & .Name & Chr(10) & "Continue?", vbInformation + vbYesNo, .Name & " C3 = " & .Range("C3").Value) = vbNo Then Exit Sub End If