在If语句中增加For循环-VBA

时间:2016-03-17 14:26:25

标签: excel vba

我需要使用循环删除电子表格中的列,而不是手动对这些列进行硬编码。但是我得到的是一个非常无用的Next而没有For错误。

Sub test()

With Application
    .ScreenUpdating = False
    .EnableEvents = False
End With

Dim colNum2 As Integer
colNum2 = 1

For x = 1 To 32

    If Range("A1").Value = "Order No." Then
        Next colNum
    ElseIf Range("B1").Value = "Line No." Then
        Next colNum
    ElseIf Range("C1").Value = "Order Qty." Then
        Next x
    ElseIf Range("D1").Value = "PO" Then
        Next x
    ElseIf Range("E1").Value = "Sched Date" Then
        Next x
    ElseIf Range("F1").Value = "Sched MFG Line" Then
        Next x
    ElseIf Range("G1").Value = "Item No." Then
        Next x
    ElseIf Range("H1").Value = "Item Width" Then
        Next x
    ElseIf Range("I1").Value = "Item Height" Then
        Next x
    ElseIf Range("J1").Value = "SL Color" Then
        Next x
    ElseIf Range("K1").Value = "Frame Option" Then
        Next x
    End If
        'Checks if the cell matches a specific string required by the sorter
        'if TRUE should skip through to the next increment of colNum

    Columns(colNum2).EntireColumn.Delete
        'uses the current number of colNum to delete the current column number
    colNum2 = colNum2 + 1

Next x
    'increments colNum by one
    'Iterates next through the loop

我觉得这样可以说Java或Python,所以我真的很恼火VBA不会让我这样做。

有人可以解释这段代码出了什么问题吗?

3 个答案:

答案 0 :(得分:3)

只需使用var = var + 1代替NextNext结束For周期。 此外,您不需要在下一行重复变量名称,因为它已经在For行中。 (For i = 0 To 5 ... Next

For x = 1 To 32

    If Range("A1").Value = "Order No." Then
        colNum = colNum +1
    ElseIf Range("C1").Value = "Order Qty." Then
        x = x + 1
    End If
Next

请记住Scott Cranner所说的,Next也会x=x+1,所以如果你只想每个周期递增一次,请改用Do While循环

x = 1
Do While x <= 32

    If Range("A1").Value = "Order No." Then
        colNum = colNum +1
    ElseIf Range("C1").Value = "Order Qty." Then
        x = x + 1
    End If
Loop

答案 1 :(得分:0)

在我看来,您希望删除与'分拣机'所需的特定字符串不匹配的所有列。在这种情况下,您可以循环遍历所有列标题标签,删除不匹配的标题标签或使用自定义从左到右的排序将所有不匹配的列放在右侧,然后删除集体

方法1 - 删除不匹配的列

Sub test1()
    Dim c As Long, vCOLs As Variant

    vCOLs = Array("Order No.", "Line No.", "Order Qty.", "PO", _
                  "Sched Date", "Sched MFG Line", "Item No.", _
                  "Item Width", "Item Height", "SL Color", "Frame Option")

    With Application
        '.ScreenUpdating = False
        '.EnableEvents = False
    End With

    With Worksheets("sheet1")
        With .Cells(1, 1).CurrentRegion
            'delete from right-to-left or risk missing one
            For c = .Columns.Count To 1 Step -1
                If IsError(Application.Match(.Cells(1, c).Value2, vCOLs, 0)) Then
                    .Columns(c).EntireColumn.Delete
                End If
            Next c
        End With
    End With

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With

End Sub

方法2 - 自定义排序,然后偏移和删除

Sub test2()
    Dim vCOLs As Variant

    vCOLs = Array("Order No.", "Line No.", "Order Qty.", "PO", _
                  "Sched Date", "Sched MFG Line", "Item No.", _
                  "Item Width", "Item Height", "SL Color", "Frame Option")

    With Application
        '.ScreenUpdating = False
        '.EnableEvents = False
        .AddCustomList ListArray:=vCOLs
    End With

    With Worksheets("sheet1")
        With .Cells(1, 1).CurrentRegion
            'custom sort to bring the important fields to the left
            .Cells.Sort Key1:=.Rows(1), Order1:=xlAscending, _
                        Orientation:=xlLeftToRight, Header:=xlNo, _
                        OrderCustom:=Application.GetCustomListNum(vCOLs)

            'offset and delete the unwanted columns
            With .Offset(0, Application.Match(vCOLs(UBound(vCOLs)), .Rows(1), 0))
                .EntireColumn.Delete
            End With
        End With
    End With

    With Application
        .DeleteCustomList .GetCustomListNum(vCOLs)
        .ScreenUpdating = True
        .EnableEvents = True
    End With

End Sub

使用任何一种方法,您只需列出要保留的列并删除其余列。

.Cells.Sort.SortFields.Add.Cells.Sort之间存在扭曲,通常会产生一些混乱。 .SortFields.Add method使用CustomOrder:=参数,Range.Sort method使用OrderCustom:=参数。这两者绝对不一样,但经常与灾难性的结果互换使用。

答案 2 :(得分:-1)

我怀疑您正在尝试根据第1行中的文本值删除列。这将为您提供所需内容,只需将要删除的所有文本引用放在CASE语句中。

Option Explicit

Sub DeleteColumns()

    Dim colNum As Integer

    colNum = 1

    Do While Range(alphaCon(colNum) & 1).Value <> ""

        Select Case Range(alphaCon(colNum) & 1).Value

            Case "ColumnIDontWant", "AnotherColumnIDontWant"

            Columns(colNum).EntireColumn.Delete

        End Select


        colNum = colNum + 1

    Loop

End Sub

Public Function alphaCon(aNumber As Integer) As String
' Fixed version 27/10/2011

Dim letterArray As String
Dim iterations As Integer

letterArray = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    If aNumber <= 26 Then

        alphaCon = (Mid$(letterArray, aNumber, 1))

    Else

        If aNumber Mod 26 = 0 Then

            iterations = Int(aNumber / 26)
            alphaCon = (Mid$(letterArray, iterations - 1, 1)) & (Mid$(letterArray, 26, 1))

        Else

            'we deliberately round down using 'Int' as anything with decimal places is not a full iteration.
            iterations = Int(aNumber / 26)
            alphaCon = (Mid$(letterArray, iterations, 1)) & (Mid$(letterArray, (aNumber - (26 * iterations)), 1))

        End If

    End If

End Function