简单的Excel VBA循环需要

我试图在Excel VBA中创build一个简单的循环来抓取行中的信息,并根据特定单元格上的值将同一信息复制到下一行(或插入一个新行)。

例如,第1行有这些值(房屋1a,3级)

然后像这样在单元格H5上创build结果

(house 1a, bottom level) (house 1a, mid level) (house 1a, top level) 

意味着房子1a的每一层被分成3排。 那么想象一下,我会随机选出10个不同级别的房子,名单不超过3个。

抱歉的括号,但这个编辑一直在想我正在写代码。

任何帮助将不胜感激。

我假设源列是列A(1),输出行是列B(2)。

一个可能的解决scheme是使用正则expression式和while循环。

要在VBA中启用正则expression式,请进入编辑器(VBE)。

  1. 点击工具标签。
  2. 点击参考
  3. 检查Microsoft VBScript正则expression式5.5

要运行代码,请创build一个单独的模块并插入:

 Sub splitCol() 'Variables used in the regular expression Dim re As New RegExp Dim mc As MatchCollection 'Variables used for row looping Dim sourceRow As Integer Dim targetRow As Integer 'Variables used for output string Dim numberOfLevels As Integer Dim currentLevel As Integer Dim houseName As String 'Regular expression patter re.Pattern = "(.+)?\,+\s+?(\d+)+\s+?levels" 'With the asumption that Row 1 are headers I'm starting at row 2 sourceRow = 2 targetRow = 2 numberOfLevels = 0 'Loop through input row until blank is found While (Cells(sourceRow, 1).Value <> "") 'Execute the regular expression Set mc = re.Execute(Cells(sourceRow, 1).Value) 'Only create output string if regular expression was able to 'executed without a problem If mc.Count > 0 Then houseName = mc(0).SubMatches(0) numberOfLevels = mc(0).SubMatches(1) currentLevel = 1 While currentLevel <= numberOfLevels Cells(targetRow, 2).Value = houseName & " , Level " & CStr(currentLevel) targetRow = targetRow + 1 currentLevel = currentLevel + 1 Wend End If sourceRow = sourceRow + 1 Wend End Sub