简体   繁体   中英

Excel VBA: Restart Loop Counter

Hi, I am trying to restart my loop counter(iColumn). I am looping through the columns to replace multiple words in a template(TemplateSheet). Is it possible to restart the loop counter after looping through all the columns(inside loop).

My only problem is after incrementing the row value, it goes back to the loop(columns) then the value of iColumn becomes 4 and terminates the inside loop.

While Sheets("DataSheet").Cells(iRow, 1).Value <> ""

   While Sheets("DataSheet").Cells(1, iColumn) <> ""

      sFind = Sheets("DataSheet").Cells(1, iColumn)

      sReplacement = Sheets("DataSheet").Cells(iRow, iColumn)

      sTemplate = Replace(sTemplate, sFind, sReplacement)

      iColumn = iColumn + 1

Wend
      Sheets("OutputSheet").Cells(iRow, 1) = sTemplate
      iRow = iRow + 1
   Wend

The problem was solved in restarting the loop counter. But now I have to overwrite the replacement function because it doesn't store the new replaced data.

Simply reset the value of iColumn to whatever your initial value needs to be. I assumed 1 .

While Sheets("DataSheet").Cells(iRow, 1).Value <> ""
   While Sheets("DataSheet").Cells(1, iColumn) <> ""
      sFind = Sheets("DataSheet").Cells(1, iColumn)
      sReplacement = Sheets("DataSheet").Cells(iRow, iColumn)
      sTemplate = Replace(sTemplate, sFind, sReplacement)
      iColumn = iColumn + 1
   Wend
   MsgBox sTemplate
   iRow = iRow + 1
   iColumn = 1
Wend

You can simplify your code a bit like this:

While Sheets("DataSheet").Cells(iRow, 1).Value <> ""
   While Sheets("DataSheet").Cells(1, iColumn) <> ""
      sTemplate = Replace(sTemplate, Sheets("DataSheet").Cells(1, iColumn), Sheets("DataSheet").Cells(iRow, iColumn))
      iColumn = iColumn + 1
   Wend
   MsgBox sTemplate
   iRow = iRow + 1
   iColumn = 1
Wend

Finally, note that the location of your MsgBox call you will only get the final value of sTemplate , not any of the intermediate values. That may, of course, be what you're after.

If sTemplate has the value that you want in the cell, then you'll need to set the cell to that data as well like so:

Sheets("DataSheet").Cells(iRow, iColumn) = sTemplate

Here's the whole loop:

While Sheets("DataSheet").Cells(iRow, 1).Value <> ""
    While Sheets("DataSheet").Cells(1, iColumn) <> ""
        sFind = Sheets("DataSheet").Cells(1, iColumn)
        sReplacement = Sheets("DataSheet").Cells(iRow, iColumn)
        sTemplate = Sheets("TemplateSheet").Cells(1, 1)
        Sheets("OutputSheet").Cells(iRow, iColumn) = Replace(sReplacement, sTemplate, sFind)
        iColumn = iColumn + 1
    Wend
    MsgBox sTemplate
    iRow = iRow + 1
    iColumn = 1
Wend

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM