2017-07-19 47 views
0

我在下面的代碼中填充主工作表中的一列(在代碼中稱爲sht)。在這張表(sht)中,我想讓C85從C85下來時碰到C列中的空單元格時停止宏。我將如何去追求這個目標?當列中的值爲空時,宏不會停止

Sub VTZ() 

Dim sht As Worksheet, sht2 As Worksheet 
Set sht = Sheets("16-Compliancy-Rebuild") 
Set sht2 = Sheets("OpmerkingBackup") 
Dim Table1 As Range 
Dim Table2 As Range 
Dim Dept_Row As Long 
Dim Dept_Clm As Long 
Dim rng As Range 
Set Table1 = sht.Range("D85:D1185") 
Set Table2 = sht2.Range("B3:B1103") 
Dept_Row = sht.Range("H85").Row 
Dept_Clm = sht.Range("H85").Column 
For Each cl In Table1 
Set rng = Table2.Find(cl, SearchDirection:=xlPrevious, LookAt:=xlWhole) 
If Not rng Is Nothing Then 
    sht.Cells(Dept_Row, Dept_Clm) = sht2.Cells(rng.Row, 6).Value 
End If 
Dept_Row = Dept_Row + 1 
Next cl 
MsgBox "Done" 
End Sub 

嘗試了很多谷歌搜索正手,似乎無法找到正確的方法來做到這一點。

+0

你說的是C列,但是你的宏根本不接觸C列。你能提供更多關於你的問題的信息嗎? –

回答

1

嘗試更新這部分...

For Each cl In Table1.cells 
Set rng = Table2.Find(cl, SearchDirection:=xlPrevious, LookAt:=xlWhole) 
If Not rng Is Nothing Then 
    sht.Cells(Dept_Row, Dept_Clm) = sht2.Cells(rng.Row, 6).Value 
else 
Exit For 'exits the loop 

End If 
Dept_Row = Dept_Row + 1 
Next cl 

我不知道如果這就是你想退出循環右側部分。另一種方式只是...

For Each cl In Table1.cells 
If Isempty(cl) then 
    Exit Sub 'this completely exits the macro 
Endif 
Set rng = Table2.Find(cl, SearchDirection:=xlPrevious, LookAt:=xlWhole) 
If Not rng Is Nothing Then 
    sht.Cells(Dept_Row, Dept_Clm) = sht2.Cells(rng.Row, 6).Value 

End If 
Dept_Row = Dept_Row + 1 
Next cl 
+1

你最後的代碼工作完美。感謝您的忍者編輯,並提供了很大的幫助。祝賀你。 – RobExcel

相關問題