VBA:在For循环的IF / Then语句中插入行

时间:2018-08-22 21:43:40

标签: excel-vba

每当列中的值发生变化时,我都试图插入两行并复制并粘贴顶部行(标题)(这是一个较大的宏中的一项较小的任务,在该宏中,我正在格式化数据并粘贴该宏数据输入到Outlook电子邮件中)。出于某种原因,尽管数据显示“ j + 1”之间的值存在明显差异,但似乎我的“ if”语句未得到满足,因此没有执行“ then”代码(即未插入任何行)和“ 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

0 个答案:

没有答案
相关问题