同一个子中的几个循环

时间:2017-12-05 15:02:34

标签: excel vba loops

我试图找出在同一个子中如何运行几个循环: 我有一组excel文件,这些文件中的每一个都必须在其A列和O列中进行一些更改,在某些条件下,每个值为“136”的单元格都必须替换为“174”:

现在我做了这个:

Sub REPLACE1()
Dim y As Integer
Dim wB As Workbook
Set FileSystemObj = CreateObject("Scripting.FileSystemObject")

Set FolderObj = FileSystemObj.GetFolder("\")

For Each fileobj In FolderObj.Files
Set wB = Workbooks.Open(fileobj.Path)

With wB.Sheets("Schedule Daily Bank Structure R")
For y = 4 To .Cells(Rows.Count, 8).End(xlUp).Row
If .Cells(y, "A") = 136 And .Cells(y, "B") = "320" Then
.Cells(y, "A") = 174

End If
Next y
End With


wB.Save
wB.Close

Next fileobj

End Sub

我的问题是,当我尝试做的时候:

Sub REPLACE1()
Dim y As Integer
Dim wB As Workbook
Set FileSystemObj = CreateObject("Scripting.FileSystemObject")

Set FolderObj = FileSystemObj.GetFolder("\")

For Each fileobj In FolderObj.Files
Set wB = Workbooks.Open(fileobj.Path)

With wB.Sheets("Schedule Daily Bank Structure R")
For y = 4 To .Cells(Rows.Count, 8).End(xlUp).Row

If .Cells(y, "A") = 136 And .Cells(y, "B") = "320" Then
.Cells(y, "A") = 174

End If    

If .Cells(y, "O") = 136 And .Cells(y, "N") = "320" Then
.Cells(y, "O") = 174


End If
Next y
End With


wB.Save
wB.Close

Next fileobj

End Sub

这意味着,在循环中包含另一个“if”条件。没有出现错误消息,但我的工作表中没有发生任何变化。

我必须错过一些东西,但我可以弄清楚到底是什么。

1 个答案:

答案 0 :(得分:1)

您的代码未格式化,您将错过很多简单的问题。我不得不格式化它,看看是否有任何遗漏。运行此代码并告诉我是否有任何错误:

Sub REPLACE1()
    Dim y As Integer
    Dim wB As Workbook
    Set FileSystemObj = CreateObject("Scripting.FileSystemObject")

    Set FolderObj = FileSystemObj.GetFolder("\")

    For Each fileobj In FolderObj.Files
        Set wB = Workbooks.Open(fileobj.Path)

        With wB.Sheets("Schedule Daily Bank Structure R")
            For y = 4 To .Cells(Rows.Count, 8).End(xlUp).Row

                If .Cells(y, "A") = 136 And .Cells(y, "B") = "320" Then
                    .Cells(y, "A") = 174
                End If

                If .Cells(y, "O") = 136 And .Cells(y, "N") = "320" Then
                    .Cells(y, "O") = 174
                End If
            Next y
        End With

        wB.Save
        wB.Close

    Next fileobj
End Sub