创build一个macros将search工作簿,然后执行一个if then else

我一直在努力工作一个我无法得到的macros。

我希望macros使用if then代码search工作簿中的所有工作表。

我想如果然后search范围C8的值为“否”,如果是的话,我希望它返回工作表的名称。

这就是我现在所拥有的,但它不工作。


With wsAddPatient For Each ws In Active.Workbook.Worksheets If ws.Visible = xlSheetVisible And Range("C8") = "No" Then .Cells(8, 2).Value = ws.Name End If 

使用Dave的代码更新:

 Sub NeedVolunteer() Set wsAddPatient = ThisWorkbook.Worksheets("Add Patient") With wsAddPatient For Each ws In ActiveWorkbook.Worksheets If ws.range("C8").Value = "No" Then .Cells(8, 2).Value = .Cells(8, 2).Value & ws.Name & ";" End If Next End With End Sub 

这工作!

最后:

 Sub NeedVolunteer() Set wsAddPatient = ThisWorkbook.Worksheets("Add Patient") Dim ws As Worksheet Dim lRow As Long iRow = 8 With wsAddPatient For Each ws In ActiveWorkbook.Worksheets If ws.Range("C8").Value = "No" Then .Cells(iRow, 2).Value = ws.Name iRow = iRow + 1 End If Next End With End Sub 

 With wsAddPatient For Each ws In ActiveWorkbook.Worksheets If ws.Visible = xlSheetVisible And ws.Range("C8") = "No" Then .Cells(8, 2).Value = ws.Name End If Next End With 

如果你没有指定range("C8")属于工作表,那么activesheet将被使用 – 因为你看起来并没有改变工作表,这意味着你总是检查同一个地方。 这应该为你sorting的问题,并把任何工作表的名称在C8中的“否”到wsAddPatient.Cells(8,2)

请记住,如果有多个工作表使用此值,则会覆盖以前的任何结果。 考虑改变

 .Cells(8,2).Value = ws.Name 

 .Cells(8,2).Value = .Cells(8,2).Value & ws.Name & ";" 

这将使您在单元格中留下一个末尾的分号,但是工作表名称与工作簿中的条件匹配的完整列表。

你很近,只是缺less一些代码。 试试这个:

 For Each ws In ActiveWorkbook.Worksheets If ws.Visible = xlSheetVisible And Range("C8") = "No" Then ws.Cells(8, 2).Value = ws.Name End If Next ws 

也许

 Dim wsNumber as String Dim i as Integer For i = 1 to 10 'change 10 to the Number of Sheets you want to check wsNumber = "Sheet" & i If Worksheets(wsNumber).Range("C8") = "no" then Worksheets("Sheet1").Range("B8") = wsNumber End If Next i 

这将返回工作表的名称“no”已被发现。为了保持简单,我只是将它返回Sheet1的单元格B8中,如果要返回表单中find“no”的名称,请使用: Worksheets(wsnumber).range("B8") = wsNumber而不是Worksheets("Sheet1").Range("B8") = wsNumber

添加

 For Each ws In ActiveWorkbook.Worksheets If ws.Range("C8") = "no" Then ws.Range("B8") = ws.Name End If Next