[英]Excel VBA: Restart Loop Counter
Hi, I am trying to restart my loop counter(iColumn). 嗨,我正在尝试重启我的循环计数器(iColumn)。 I am looping through the columns to replace multiple words in a template(TemplateSheet).
我循环遍历列以替换模板中的多个单词(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. 我唯一的问题是在递增行值后,它返回到循环(列),然后iColumn的值变为4并终止内部循环。
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. 只需将
iColumn
的值重置为您需要的初始值即可。 I assumed 1
. 我假设
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. 最后,请注意,
MsgBox
调用的位置只能获得sTemplate
的最终值,而不是任何中间值。 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: 如果sTemplate具有您在单元格中所需的值,那么您需要将单元格设置为该数据,如下所示:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.