首页 > 解决方案 > 为什么在运行我的代码时会跳过一行?

问题描述

我在运行此代码时遇到问题。每当我在按 F8 的同时逐步执行此操作时,它都会起作用,但每当我运行它时,它都会跳过Rows(R).EntireRow.Insert最重要的行。谢谢!

Sub AddARow()
    Dim R As Long
    Dim FoundCell As Range
    Dim revF As Long
    Dim nbUnit As Long
    Dim moyenneM As Long
    
    Set FoundCell = Sheets("Étude").Range("C1:C200").Find(what:="xxxxx")
    R = ((FoundCell.Row) + 2)
    
    Rows(R).EntireRow.Insert
    
    Cells(R, 3).Value = "Moyenne mensuelle par condo"
    
    nbUnit = Cells((R + 4), 4).Value
    
    For i = 4 To 33
        revF = Cells((R - 1), i).Value
        moyenneM = revF / nbUnit
    
        Cells(R, i).Value = moyenneM / 12
    Next
    
    Call AutoFill_TB
End Sub

标签: excelvba

解决方案


明确提供您正在执行操作的工作表名称是一种很好的做法。您可以通过为工作表和工作簿声明一个变量并设置该变量来做到这一点。我已修改您的代码以提供这些变量。如果您遵循此操作,您将不会遇到问题,您目前正在获得:

Sub AddARow()
    Dim R As Long
    Dim FoundCell As Range
    Dim revF As Long
    Dim nbUnit As Long
    Dim moyenneM As Long
    Dim sh As Worksheet
    Dim wkb As Workbook
    
    Set wkb = ThisWorkbook
    Set sh = wkb.Worksheets("Étude")
    
    Set FoundCell = sh("Étude").Range("C1:C200").Find(what:="xxxxx")
                R = ((FoundCell.Row) + 2)
                
    
    sh.Rows(R).EntireRow.Insert    ' assuming you want to insert in Sheet - Étude
    
    
    sh.Cells(R, 3).Value = "Moyenne mensuelle par condo"
    
    nbUnit = sh.Cells((R + 4), 4).Value
    
    
    For i = 4 To 33
    
        revF = sh.Cells((R - 1), i).Value
        moyenneM = revF / nbUnit
    
        sh.Cells(R, i).Value = moyenneM / 12
    
    Next
    
    Call AutoFill_TB
End Sub

推荐阅读