VBA将两个循环合并成一个消息框

这里是提示:查找列表中有多less个Zachary(使用你喜欢的任何循环),同时查找列表中有多less个客户

我能够做两个独立的循环,但是当我试图合并它们时,它们不能在一个消息框中工作。

'find多lessZachary在列表中(使用任何你喜欢的循环)

counter = 0 zCounter = 0 With Workbooks("C14-Do While Test - final.xlsm").Worksheets("Customers") Do While counter < 500 counter = counter + 1 If .Range("B1:B500").Cells(counter) = "Zachary" Then zCounter = zCounter + 1 End If Loop MsgBox "There are " & zCounter & " Zacharys in the list" End With 

'同时发现有多less客户在列表中

 counter = 0 notFound = True With Workbooks("C14-Do While Test - final.xlsm").Worksheets("Customers") Do While notFound counter = counter + 1 If .Range("B1:B500").Cells(counter) = "" Then notFound = False End If Loop MsgBox "There are " & counter & " customers in the list" End With 

尝试以下仅一个循环,并引入一个variablesallCustomers来保存在循环范围内假定为非空白单元格的客户的数量。

VBNewline与Msgbox一起使用来在单独的行上打印两个计数。

 counter = 0 zCounter = 0 allCustomers = 0 ' variable to hold all customers With Workbooks("C14-Do While Test - final.xlsm").Worksheets("Customers") Do While counter < 500 counter = counter + 1 If .Range("B1:B500").Cells(counter) = "Zachary" Then zCounter = zCounter + 1 End If If .Range("B1:B500").Cells(counter) <> vbNullString Then allCustomers = allCustomers + 1 End If Loop MsgBox "There are " & zCounter & " Zacharys in the list" & vbNewLine & "There are " & allCustomers & " customers in the list" End With 

你可以把这个.Range("B1:B500").Cells(counter)放到一个variables中来加速你的循环。