excel - 如何使用 VBA 在列中插入组上方/下方的行
问题描述
我什至为此启动宏都遇到了麻烦。任何帮助将不胜感激。
参考下面的示例,是否可以找到组的第一个值并在其上方插入一行。如:在A列中找到第一个“苹果”并在上方插入行,在A列中找到第一个“香蕉”并在上方插入行等。查找组中的最后一个值并在下方插入行也可以,如:在A列中找到最后一个“苹果”并在下面插入行。
还需要的是,如果 A 列中没有“苹果”,则转到“香蕉”。
A
1 apple
2 apple
3 apple
4 apple
5 banana
6 banana
7 banana
8 banana
9 banana
10 orange
11 orange
12 orange
13 orange
14 orange
15 orange
解决方案
这是一个应该做你正在寻找的子程序。
Sub main()
Dim lastRow As Long
Dim firstFruit As String
With Sheets("Sheet1")
'find last row containing a value
lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
'initialize our first fruit as the first cell with a value.
firstFruit = .Cells(1, 1).Value
For ctr = 1 To lastRow
If (.Cells(ctr, 1).Value <> firstFruit) Then 'we've found a new fruit
.Rows(ctr & ":" & ctr).Insert 'insert our row above where we found it
firstFruit = .Cells(ctr + 1, 1).Value 'set our fistFruit to equal the value of the new fruit
lastRow = lastRow + 1 'add +1 to lastRow because we've added a new one
End If
Next ctr
End With
End Sub
推荐阅读
- visual-studio-2019 - Microsoft Visual Studio Community 2019 CodeLens 参考计数器不正确
- gams-math - 如何修复 Gams 中的错误 149?(输入为常量的不受控集)
- javascript - 如何在“row-fluid div”中的应用程序根组件中调用我的按钮组件
- sql - 如何在元数据库的 LIKE 查询中使用变量?
- python - 错误:标签 [0] 不在 [index] 中
- python - IOError:[Errno 2] 没有这样的文件或目录:(Python:即使文件确实存在,我也会遇到此错误)
- java - 当我使用 Apache Storm 运行我的 JAR 时,为什么会引发 java.lang.NoClassDefFoundError ?(org/apache/storm/kafka/spout/KafkaSpoutConfig)
- vector - 如何将两个 Rust 向量按三个块交错成一个新向量?
- laravel - 从 laravel 的视图中传递值和调用控制器
- docker - 在 Docker-Compose 和 GitLab-CI 之间共享环境变量