在选定范围内循环尝试获取偏移量的单元格值

我有一个用户窗体,其中包含范围select字段和一个button。 还有一个XML模板文件在几个地方有“###”,将被我们下面的循环replace。

按下button,窗体将循环显示所选范围,并根据XML模板为所选(1维)范围内的每个单元格创buildXML文件,其名称是该范围内正在循环的当前单元格。

无论相邻单元格的值(当前循环项目的右边两列)如何,每个循环迭代都会执行查找和replace操作,以写入每个文件。

ColA ColB ColC ABC (empty) 123 // loop should create ABC.xml, DEF.xml, GHI.xml with DEF (empty) 456 // data inside 123, 456, 789 respectively in each .xml GHI (empty) 789 // instead all three .xml will have 123 which is not what we want 

生成的文件具有合适的名称, 但所有文件都具有相同的数据 – 与选定区域相邻的第一个单元格的值。 就好像循环正确地在范围内循环,但是在整个循环持续时间内(存储在sAdjacentVal中)引用了第一个相邻的单元格。

 For Each i In selectedRange sFileName = i.Value & ".xml" sFullFileName = sPath & LCase(sFileName) 'Grab adjacent value 2 rows to the right of the current loop item sAdjacentVal = i.Offset(0, 2).Value sTemplateXML = Replace(sTemplateXML, "###", sAdjacentVal) Set oFileStream = FSO.CreateTextFile(sFullFileName, True, True) oFileStream.Write sTemplateXML oFileStream.Close Next i 

一旦你在第一个循环中执行第一个replace,

 sTemplateXML = Replace(sTemplateXML, "###", sAdjacentVal) 

然后, sTemplateXML不再包含完成下一个循环replace所需的###

 dim tmp as string For Each i In selectedRange sFileName = i.Value & ".xml" sFullFileName = sPath & LCase(sFileName) 'Grab adjacent value 2 rows to the right of the current loop item sAdjacentVal = i.Offset(0, 2).Value tmp = Replace(sTemplateXML, "###", sAdjacentVal) Set oFileStream = FSO.CreateTextFile(sFullFileName, True, True) oFileStream.Write tmp oFileStream.Close Next i