excel - 无法弄清楚为什么 VBA 在验证 If 语句时退出我的 For-Next 循环
问题描述
好的,所以我最近进入了 VBA 编程,我一直在尝试编写一些代码来执行以下操作:
- 循环浏览包含正确或错误陈述的列(在我的情况下为“K”列)
- 如果为真,则收集相应的名称(“C”列)并创建一个相应命名的工作表
就这样
所以这是我写的代码:
Sub Generate_Attribute_Table()
Dim LastRow As Long
Dim i As Integer
Dim Nom As String
LastRow = Range("A1").End(xlDown).Row
For i = 2 To LastRow
If (Cells(i, "K").Value) Then
Nom = Worksheets(1).Cells(i, "C").Value
ActiveWorkbook.Sheets.Add(After:=Worksheets(Sheets.Count)).Name = Nom
Else
Cells(i, "K").Select
End If
Next i
End Sub
它似乎工作得很好,但即使列中有其他 True ,它也会在生成第一张表后停止。
else 案例用于调试目的,因为我想看看发生了什么,它确认只要验证了 if 语句,循环就会停止。
我尝试使用“直到”循环来做同样的事情,但它的作用是一样的。
我在这里想念什么?我在网上找不到任何答案,所以任何帮助都会非常好。
提前致谢。
解决方案
使用列表中的名称添加工作表
- 如果工作表名称无效,以下内容仍会引发错误。
Option Explicit
Sub Generate_Attribute_Table()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = wb.Worksheets(1) ' wb.Worksheets("Sheet1")
' This (usually preferred) way will allow empty cells in the column.
Dim LastRow As Long: LastRow = sws.Cells(sws.Rows.Count, "A").End(xlUp).Row
Dim dsh As Object
Dim Nom As String
Dim i As Long
For i = 2 To LastRow
' If you use '(sws.Cells(i, "K").Value)', an error will occur
' if there is not a boolean in the cell.
If sws.Cells(i, "K").Value = True Then
Nom = sws.Cells(i, "C").Value
' Attempt to create a reference to the sheet named 'Nom'.
Set dsh = Nothing
On Error Resume Next
Set dsh = wb.Sheets(Nom)
On Error GoTo 0
' Test for existence.
If dsh Is Nothing Then ' A sheet named 'Nom' doesn't exist.
wb.Worksheets.Add(After:=wb.Sheets(wb.Sheets.Count)).Name = Nom
'Else ' A sheet named 'Nom' already exists.
End If
End If
Next i
End Sub
推荐阅读
- css - CSS Grid 容器缩小到项目大小
- r - 随时间模拟的生/死模型
- ruby - 从多个类的实例数组中获取最小值
- c# - 在 Default.aspx WebForms 中为特定页面显示不同的图像
- python - XGBoost 预测不同操作系统之间的差异
- django - 在 django 中创建对象时使用 upload_to 函数
- node.js - 如何在nods js中将html字符串转换为word doc
- javascript - React Native 中的缩放视图
- javascript - 使用 Selenium 控制使用 javascript 和 Selenium 创建的动态表
- c - sscanf 和 printf 覆盖值