首页 > 解决方案 > 无法弄清楚为什么 VBA 在验证 If 语句时退出我的 For-Next 循环

问题描述

好的,所以我最近进入了 VBA 编程,我一直在尝试编写一些代码来执行以下操作:

就这样

所以这是我写的代码:

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 语句,循环就会停止。

我尝试使用“直到”循环来做同样的事情,但它的作用是一样的。

我在这里想念什么?我在网上找不到任何答案,所以任何帮助都会非常好。

提前致谢。

标签: excelvbafor-loopif-statement

解决方案


使用列表中的名称添加工作表

  • 如果工作表名称无效,以下内容仍会引发错误。
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

推荐阅读