Excel VBAtypes与If函数不匹配

我对VBA很陌生,上周一直在教我自己。 我已经承担了一个对我来说可能有点复杂的任务。

我有一个列A – AE的文件,我需要通过这个文件,并将信息移动到单独的表,这取决于它是什么。 我现在试图在移动信息之前使用一个需要匹配2个要求的IF语句。 我可以得到每个单独的要求,但不能一起工作,因为不断收到types不匹配错误。

我不知道我做错了什么。 任何帮助都感激不尽。

Sub copyrows() Dim Test As Range, Cell As Object Set Test = Range("G2:Z4000") 'Substitute with the range which includes your True/False values For Each Cell In Test If IsEmpty(Cell) Then Exit Sub End If If Cell.Value = "Refund" And "Commission" Then Cell.EntireRow.Copy Sheet3.Select 'Substitute with your sheet ActiveSheet.Range("A65536").End(xlUp).Select Selection.Offset(1, 0).Select ActiveSheet.Paste End If Next End Sub 

If Cell.Value = "Refund" And "Commission" Then

应改为阅读:

If Cell.Value = "Refund" Or Cell.Value = "Commission" Then

您必须明确每个由布尔运算符(如AND或OR)分隔的条件。

@IanL在上面的答案中已经提到了你的错误的原因

但是,你的代码远没有被优化。

你可以replace你的5行:

  Cell.EntireRow.Copy Sheet3.Select 'Substitute with your sheet ActiveSheet.Range("A65536").End(xlUp).Select Selection.Offset(1, 0).Select ActiveSheet.Paste 

用1:

 Cell.EntireRow.Copy Destination:=Sheet3.Range("A65536").End(xlUp).Offset(1) 

不使用SelectActiveSheetSelection ,只使用完全限定的Range对象。