在切换工作表vba时while循环出错1004

所以我对vba相当陌生,而且在工作上只花了大约一个月的时间。 我一直有这个问题,当我试图运行我的macros时,得到错误1004“应用程序定义,或对象定义的错误”。 我想要做的是通过一个数据列表,并找出行是否有一个特定的代码附加到它。 如果是这样,我想在该行上移动一个date到一个新的工作表。

Sub k0Pop() Dim source As Long Dim servR As Integer Dim servC As Integer Dim patID As Integer Dim spot1 As Integer Dim spot2 As Integer Dim sht1 As Worksheet Dim sht2 As Worksheet Set sht1 = Sheets("Sheet2") Set sht2 = Sheets("Sheet4") servR = 3 For source = 3 To 100000 servC = 2 While sht2.Cells(source, 2) < sht2.Cells(patID, 15) source = source + 1 Wend While Cells(source, 2) = Cells((source + 1), 2) If Cells(source, 6) = "K045A" Then spot = source End If source = source + 1 Wend If Cells(source, 6) = "K045A" Then spot = source source = source + 1 End If spot2 = source source = spot1 While (Cells(spot, 5) - Cells(source, 5)) < 365 source = source - 1 Wend While source < spot sht1.Cells(servR, servC) = sht2.Cells(source, 5) source = source + 1 servC = servC + 1 Wend sht1.Cells(servR, 14) = sht2.Cells(spot, 5) source = spot2 servR = servR + 1 patID = patID + 1 Next End Sub 

看起来像patID是0,这是一个无效的列。 使用F8单循环。 将鼠标hover在variables上以查看其值。 使用debug.print来显示中间数据。