vba - 当我单步执行时,我的 vba 循环会拉回所有正确的数据,但当我运行宏时,它不会

标签 vba excel do-loops

我尝试构建一个循环,在满足条件时拉回某些数据,然后将结果发布在我的“主”表中。

不幸的是,当您运行宏时,它不会拉回所有数据。

但是,在我看来,这非常奇怪,当你逐步执行它时就会发现。

代码中的任何位置都没有错误消息,并且如果您单步执行/仅运行宏,代码会完整运行。

我已在下面发布了我的代码:

Sub Loop_Data()
    'BR stands for Blank Row
    Dim i As Integer, j As Integer, k As Integer, m As Integer, BRMAin As Integer, BRData As Integer, BRPhysNot As Integer, _
    SearchRange As Range, strID As String, ExtEnd As Integer, FindRow As Range

    BRMAin = Sheets("Main").Cells(Rows.Count, "W").End(xlUp).Row
    BRData = Sheets("Data").Cells(Rows.Count, "A").End(xlUp).Row
    BRPhysNot = Sheets("PhysNot").Cells(Rows.Count, "A").End(xlUp).Row

    Set SearchRange = Sheets("Data").Range("A3:A" & BRData)
    Sheets("CoData").Activate
    'assign j for number of rows (units) and i to start at 6 (column J) and end at 21

    For j = 2 To 48
        i = 35
        Do Until i = 52
                'criteria 
            If Cells(j, i - 1).Interior.Color <> RGB(51, 51, 51) And Cells(j, i - 1) > 0 And Cells(j, i).Interior.Color = RGB(51, 51, 51) Then
                'find duration o
                m = 0
                Do While Cells(j, i + m).Interior.Color = RGB(51, 51, 51)
                    m = m + 1
                Loop
                'check that the flagged is definitely matching criteria
                If Cells(j, i + m) = 0 Then
                    'set string ID as the string of uni & period to find in the helper column of Data sheet
                    'set k as row which that occurs in
                    strID = Cells(1, i) & Cells(j, 3)
                    Set FindRow = SearchRange.Find(strID)
                    k = FindRow.Row
                    'Pull back data into main sheet
                    ThisWorkbook.Sheets("Main").Range("X" & BRMAin + 1) = Sheets("Data").Cells(k, 8)
                    ThisWorkbook.Sheets("Main").Range("V" & BRMAin + 1) = Sheets("Data").Cells(k, 4)
                    ThisWorkbook.Sheets("Main").Range("W" & BRMAin + 1) = Sheets("Data").Cells(k, 2)
                    ThisWorkbook.Sheets("Main").Range("Y" & BRMAin + 1) = m
                    ThisWorkbook.Sheets("Main").Range("Z" & BRMAin + 1) = Sheets("CoData").Cells(1, i)
                End If
            End If
            i = i + 1
        Loop
    Next j
End Sub   

最佳答案

如果 WaitDoEvents 不起作用,而不是使用

Set FindRow = SearchRange.Find(strID)
k = FindRow.Row

你可以选择

k = 0
For Each SearchCell In SearchRange
    If SearchCell.Text = strID Then k = SearchCell.Row
Next

关于vba - 当我单步执行时,我的 vba 循环会拉回所有正确的数据,但当我运行宏时,它不会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41938975/

相关文章:

excel - 如何使用 VBA 在浏览器中打开 URL?

asp.net - 将 ExcelPackage 文件发送给用户

vba - 生成日期序列

performance - SAS:通过 proc 导入提高 do 循环的速度

arrays - 内部数组矩阵的有效DO循环

arrays - 在 VBA 中仅粘贴二维数组的特定索引

vba - 如何知道Word中右键下的单词

c - 使用循环语句进行 C 练习 : Write code to reverse numbers with do-while statement

excel - 以矩阵 VBA 形式返回单元格

VBA 如何在按下表单按钮时强制函数返回