首页 > 解决方案 > VBA:在 For 循环中的 IF/Then 语句中插入行

问题描述

每次列中的值发生变化时,我都尝试插入两行并复制并粘贴顶行(标题)(这是一个更大的宏中的一个较小的任务,我在其中格式化数据并将该数据粘贴到 Outlook电子邮件)。出于某种原因,似乎我的“if”语句没有得到满足,因此没有执行任何“then”代码(即没有插入任何行),尽管数据显示“j+1”之间的值存在明显差异和“j+2”,所以应该在它们之间插入行。根据以下内容,您是否看到我的 if 语句有缺陷的任何原因?

Function RangetoHtml(rng As Range)

Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
Dim TopR As Double
Dim j As Long
Dim LastR As Double

TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"


rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
    .Cells(1).PasteSpecial Paste:=8
    .Cells(1).PasteSpecial xlPasteValues, , False, False
    .Cells(1).PasteSpecial xlPasteFormats, , False, False
        Range("B1").Select

        For j = 1 To 100
            If Cells(j + 1, 1).Value <> Cells(j + 2, 1).Value And Cells(j + 2, 1) <> 0 Then
            Rows(j + 2).Resize(2).EntireRow.Insert
            Rows("1").Copy
            Rows(j + 3).PasteSpecial xlPasteFormats
            Rows(j + 3).PasteSpecial xlPasteValues              
            j = j + 2
            End If
        Next

我在下面的代码中添加了这个代码,用于测试我的代码,它完全符合我的要求。我真的看不出上面的代码和下面的代码有什么区别,这似乎根本没有意义:

Sheets("Sheet1").Select
Range("E1").Select
    For j = 1 To 100
        If Cells(j + 1, 1).Value <> Cells(j + 2, 1).Value And Cells(j + 2, 1) <> 0 Then
        Rows(j + 2).Resize(2).EntireRow.Insert
        Rows("1").Copy
        Rows(j + 3).PasteSpecial xlPasteFormats
        Rows(j + 3).PasteSpecial xlPasteValues
        j = j + 2
        End If
    Next

标签: excelvba

解决方案


推荐阅读