2017-12-27 489 views
0

我在Excel中創建了一個搜索表格,我想用VBA代碼搜索工作簿其餘部分中的特定單詞。這是我的表格的一個例子。VBA搜索表格排除空白單元格

水果 商店 區

我已經設置這些值作爲一個字符串,但我有具有一個項目的空白,然後運行宏麻煩。所以,如果我只想找到水果和麪積,它不會運行,因爲商店是空白的。有沒有一種方法可以搜索工作簿而不必填寫每行?

這是我用來複制數據的代碼。

finalrow = Cells(Rows.Count, 1).End(xlUp).Row 



For i = 1 To finalrow 
If Cells(i, 1) = Fruits And Cells(i, 2) = Store And Cells(i, 3) = Area Then 
Range(Cells(i, 1), Cells(i, 3)).Copy 
ssheet.Select (Workbook sheet to paste) 
Range("A100").End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues 
+0

的還是給了我一個結果,對於任何兩個詞,我希望它返回一個只具有兩個標準 – Tara

+0

如何做價值您可以確定最終需要哪個標準。無論「Store」是空白還是填充,您總是希望它僅查找「Fruit」和「Area」存在的時間? –

+0

你好,我希望它找到水果和麪積匹配的值,即使商店留空。 – Tara

回答

2

使用IIF():

If IIF(Fruits<>"",Cells(i, 1) = Fruits,True) And _ 
    IIF(Store<>"",Cells(i, 2) = Store,True) And _ 
    IIF(Area<>"",Cells(i, 3) = Area,True) Then 

同時請避免使用選擇的。也只是想值時只分配值,並跳過剪貼板:

With ActiveSheet 
    finalrow = .Cells(Rows.Count, 1).End(xlUp).Row 

    For i = 1 To finalrow 
     If IIf(Fruits <> "", .Cells(i, 1) = Fruits, True) And _ 
      IIf(Store <> "", .Cells(i, 2) = Store, True) And _ 
      IIf(Area <> "", .Cells(i, 3) = Area, True) Then 

      ssheet.Range("A100").End(xlUp).Offset(1, 0).Resize(1, 3).Value = .Range(.Cells(i, 1), .Cells(i, 3)).Value 
     End If 
    Next i 
End With 
+0

這不起作用,有什麼我失蹤? – Tara

+0

你是什麼意思,沒有工作。這可能是很多事情。 –

+0

你好,最後一部分沒有工作。這是說.Range和.Cell是無效或無資格的參考 – Tara