简体   繁体   English

在单元格中写入值后,VBA停止运行

[英]VBA stops running when value is written in a cell

I am organizing a dirty text in an organised table. 我正在有组织的表格中整理脏文字。 And this code stops when the cell the marked line is completed. 并且该代码在单元格标记的行完成时停止。 Can you help me to make it continuing the loop? 您能帮我使其继续循环吗?

Private Sub CommandButton1_Click()    
    Dim sh As Worksheet
    Dim sh7 As Worksheet

    Dim CNAME As String

    Set sh = Worksheets("Sheet6")
    Set sh7 = Worksheets("Sheet7")    
    lr = sh.Cells(Rows.Count, 1).End(xlUp).Row

    For n = 1 To lr
        If InStr(1, sh.Cells(n, 1), "CALL:") = 1 Then
            CNAME = sh.Cells(n, 7).Value    
            Ci = sh.Cells(n + 1, 7).Value    
            Cpd = sh.Cells(n + 1, 7).Value    
        Else
            If InStr(1, sh.Cells(n, 1), "Topic:") = 1 Then
                T = sh.Cells(n, 2)
                Tpd = sh.Cells(n + 1, 2)
                Types = sh.Cells(n + 4, 2)
                DM = sh.Cells(n + 5, 2)
                D = sh.Cells(n + 5, 4)
                OD = sh.Cells(n + 6, 2)
                lr7 = sh7.Cells(Rows.Count, 1).End(xlUp).Row
                sh7.Cells(lr7 + 1, 1).Value = CNAME '********This is the last line it runs.
                sh7.Cells(lr7 + 1, 2).Value = Ci
                sh7.Cells(lr7 + 1, 3).Value = Cpd
                sh7.Cells(lr7 + 1, 4).Value = T
                sh7.Cells(lr7 + 1, 5).Value = Tpd
                sh7.Cells(lr7 + 1, 6).Value = Types
                sh7.Cells(lr7 + 1, 7).Value = DM
                sh7.Cells(lr7 + 1, 8).Value = D
                sh7.Cells(lr7 + 1, 9).Value = OD
            End If  
        End If
    Next n
End Sub

You should get in the habit of defining all variables and supplying a default value. 您应该养成定义所有变量并提供默认值的习惯。

EDIT: It seems my original conclusion was incorrect. 编辑:看来我最初的结论是不正确的。 Upon further inspection I see what might be an issue in your code. 经过进一步检查,我发现您的代码中可能存在问题。 Both times where you are trying to get the last row, you are using Rows.Count as a parameter. 两次尝试获取最后一行时,都使用Rows.Count作为参数。

Maybe change these 也许改变这些

lr = sh.Cells(Rows.Count, 1).End(xlUp).Row
lr7 = sh7.Cells(Rows.Count, 1).End(xlUp).Row

To this (note that I use the sheet variable in the first param) 为此(请注意,我在第一个参数中使用了工作表变量)

lr = sh.Cells(sh.Rows.Count, 1).End(xlUp).Row
lr7 = sh7.Cells(sh7.Rows.Count, 1).End(xlUp).Row

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM