excel - 满足条件时重置循环excel vba
问题描述
我有一张excel表格。我想在满足条件时重置循环,因为我有两个条件。但是,我想在这个解决方案网站的 for 循环旁边实施步骤,当满足条件时重置一个 for 循环 vba。它不起作用,因为它仅适用于数字而不是 A1。解决此问题的解决方案是什么?谢谢你。
Sub run()
Set MR = Range("A1:Q1")
'Loop through the cell in the first row
For Each cell In MR
If cell.Value = "First Discovered" Or cell.Value = "Last Observed" Then cell.EntireColumn.Delete
Next cell
End Sub
解决方案
如果要查看第一行的列,则无需重置循环。A:Q
关键是避免在循环内删除,因为这会在循环范围内产生变化。
以下解决方案将遍历您的范围并将目标单元格添加到Union
(单元格集合),一旦循环完成,它将删除所有单元格的列Union
还,
添加Option Explicit
. 你需要声明你的变量并且Option Explicit
会强制你这样做。这也间接地充当了一个方便的拼写检查器。
最后一件事:我将您的变量 ' cell
' 更改为 ' myCell
' 以避免与已经存在的对象混淆Cells
Option Explicit
Sub run()
Dim MR As Range, myCell As Range, DeleteMe As Range
Set MR = Range("A1:Q1")
For Each myCell In MR
If myCell = "First Discovered" Or myCell = "Last Observed" Then
If DeleteMe Is Nothing Then
Set DeleteMe = myCell
Else
Set DeleteMe = Union(DeleteMe, myCell)
End If
End If
Next myCell
If Not DeleteMe Is Nothing Then DeleteMe.EntireColumn.Delete
End Sub
推荐阅读
- javascript - 将 gatsby-node 文件重构为单独的文件不起作用
- reactjs - TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“行类型”
- database - 如何在 Postgresql 中存储 300M 条记录以运行效率查询
- bash - WSL:无法在路径中运行带有点斜杠 ./ 的可执行文件
- r - 如何反转一个完整的矩阵?
- python - 等待代码执行是否在时间限制之前完成,如果没有在限制内完成则中止
- python - 比较两个列表中的值并从第三个列表中返回相似或最接近的值
- r - 如何用缺失值前后的平均值填充向量中的缺失值
- java - 没有可用的“ru.spb.repository.UserRepository”类型的合格bean:预计至少有1个有资格作为自动装配候选者的bean
- javascript - 对 DataTable 的默认更改