当Column中的值为空时,宏不会停止

时间:2017-07-19 11:55:04

标签: excel vba excel-vba excel-2013

我使用下面的代码填充了我的主要工作表中的一列(在代码中称为sht)。在这张表(sht)中,我希望宏在从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

在正手上尝试了很多谷歌搜索,似乎无法找到正确的方法来做到这一点。

1 个答案:

答案 0 :(得分: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