excel - 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
解决方案
推荐阅读
- python - 调整根窗口大小时如何使弹出窗口小部件上的小部件与弹出窗口保持一致
- javascript - 按公共属性(日期)汇总对象数组
- bash - 使用与父用户相同的 UID/GID 运行 docker 或 docker-compose 的简单方法?
- python - 安装 Conda 后如何管理 PyCharm 制作的虚拟环境?
- module - 了解如何扩展 Julia 模块
- c# - OpenID Connect:如何在认证后检索用户信息和创建原理
- python - 如何记忆/散列 **kwargs(或一般的字典)以用作键
- javascript - 有没有办法设置适用于 Safari 的 cookie?
- django - Django静态图像显示然后不显示,视图共享静态徽标图像所在的基本Html文件
- python - 多处理功能不停止