Excel-VBA,For循环语法,“for”和“next x”的放置

时间:2015-05-07 14:41:53

标签: vba excel-vba excel

Sub test1()
Dim Str As String
Dim Search As String
Dim X As Long
Dim Y As Long


X = 2
For Y = 2 To 6

Str = Worksheets("sheet1").Cells(X, 5).Value
Search = Worksheets("FDSA").Cells(Y, 5).Value


    If Worksheets("sheet1").Cells(X, 4).Value = Worksheets("FDSA").Cells(Y, 3).Value And InStr(Search, Str) > 0 Then
        Worksheets("sheet1").Cells(X, 6).Value = "ok"
    Else

    End If
 Next Y


End Sub

经过大约一周的学习和Excel VBA失败后,我认为我非常接近我想要它做的事情。我只需要对我的最后一个循环进行一些帮助。

上面的代码完全符合我的要求。我用一个值硬编码X来调试它。我现在需要循环X来遍历行中的每个单元格并执行相同的操作。

2 个答案:

答案 0 :(得分:0)

你可以这样做,在循环内循环。

Sub test1()

Dim Str As String
Dim Search As String
Dim X As Long
Dim Y As Long


lastcolumn = Sheets("Sheet1").Range("XFD1").End(xlToLeft).Column
'I don't how you data looks like... If there is always same amount of columns you can hard-code it... or calculate the last one like this..



For Y = 2 To 6

For X = 2 To lastcolumn 'start of second loop



Str = Worksheets("sheet1").Cells(X, 5).Value
Search = Worksheets("FDSA").Cells(Y, 5).Value

If Worksheets("sheet1").Cells(X, 4).Value = Worksheets("FDSA").Cells(Y, 3).Value And InStr(Search, Str) > 0 Then
    Worksheets("sheet1").Cells(X, 6).Value = "ok"
Else

End If

Next X

Next Y

End Sub

答案 1 :(得分:0)

Sub test1() Dim Str As String Dim Search As String Dim X As Long D Y Y Long

对于X = 2到92 Str =工作表(“sheet1”)。单元格(X,5).Value

If Worksheets("sheet1").Cells(X, 6).Value = "" Then

    For Y = 2 To 96
    Search = Worksheets("FDSA").Cells(Y, 5).Value

            If Worksheets("sheet1").Cells(X, 4).Value = Worksheets("FDSA").Cells(Y, 3).Value And InStr(Search, Str) > 0 Then
                Worksheets("sheet1").Cells(X, 6).Value = "row" & Y
                Worksheets("Sheet1").Cells(X, 6).Interior.Color = RGB(0, 200, 0)

            Else

            End If

    Next Y

Else

End If

    If Y = 97 And Worksheets("sheet1").Cells(X, 6).Value = "" Then
    Worksheets("sheet1").Cells(X, 6).Value = "N/A"
    Worksheets("sheet1").Cells(X, 6).Interior.Color = RGB(200, 0, 0)
    End If

下一个X

End Sub

想出来,无论哪种方式:)