如果其他VBA代码不起作用

我是VBA的新手,而且我通常会使用我需要的代码,但事实certificate这很困难。 我正在尝试创build一个search特定名称的macros,并将该名称的所有行复制并粘贴到另一个表单中。 这工作得很好,但我也想要一个消息框,当名称不存在时出现。 我添加了一些代码,现在它只显示消息框,即使名称实际上在那里。 以下是我的代码。 非常感谢任何帮助或信息。

Private Sub CommandButton1_Click() Application.ScreenUpdating = False a = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row For i = 2 To a If Worksheets("Sheet1").Cells(i, 1).Value = "Aquino, Ervic" Then Worksheets("Sheet1").Rows(i).Copy Worksheets("Ervic Aquino").Activate b = Worksheets("Ervic Aquino").Cells(Rows.Count, 1).End(xlUp).Row Worksheets("Ervic Aquino").Cells(b + 1, 1).Select ActiveSheet.Paste Worksheets("sheet1").Activate Application.CutCopyMode = False Worksheets("Ervic Aquino").Activate Range("A1:K1").Select Range(Selection, Selection.End(xlDown)).Select Application.CutCopyMode = False Selection.Borders(xlDiagonalDown).LineStyle = xlNone Selection.Borders(xlDiagonalUp).LineStyle = xlNone With Selection.Borders(xlEdgeLeft) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlEdgeTop) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlEdgeBottom) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlEdgeRight) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlInsideVertical) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlInsideHorizontal) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With Range("I2").Select Range(Selection, Selection.End(xlToRight)).Select Range(Selection, Selection.End(xlDown)).Select Selection.ClearContents Range("H1").Select Selection.End(xlDown).Select ActiveCell.Offset(1).Select Selection.Font.Bold = True Dim LR As Long LR = Range("H" & Rows.Count).End(xlUp).Row Range("H" & LR + 1).Formula = "=SUM(H2:H" & LR & ")" Cells.Select Cells.EntireColumn.AutoFit Range("A2").Select 'If there is no activity do nothing Else MsgBox "No Activity This Month" 'End Loop Exit For End If Next Application.ScreenUpdating = True End Sub 

如果任何行不包含"Aquino, Ervic" ,那么您当前的代码显示"No Activity This Month"消息"Aquino, Ervic"但是如果没有任何行包含该string,则只希望显示消息。

最简单也可能是最有效的方法是首先执行testing,然后只处理每一行,如果存在条目:

 Private Sub CommandButton1_Click() Application.ScreenUpdating = False If Application.CountIf(Worksheets("Sheet1").Columns(1), "Aquino, Ervic") = 0 Then MsgBox "No Activity This Month" Else a = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row For i = 2 To a If Worksheets("Sheet1").Cells(i, 1).Value = "Aquino, Ervic" Then Worksheets("Sheet1").Rows(i).Copy '... Cells.EntireColumn.AutoFit Range("A2").Select End If Next End If Application.ScreenUpdating = True End Sub 

我也强烈build议阅读通过问题如何避免使用selectExcel VBA中 。 那些SelectActivate陈述将在未来引起你很多的问题,所以最好现在投入一些时间来学习如何摆脱它们。