复制标准VBA上的行

时间:2016-04-21 15:11:02

标签: excel vba excel-vba

我需要一些想法来复制符合条件的行。

我有这样的数据:

   A        B                          C     D
1   Country  Brand                      Model Year
2   France   Peugeot, Citroen (France)  Car   2003
3   Germany  VW, Opel, BMW (Germany)    Car   2003
...

目标是每个带有它参数的汽车品牌都是分开的/ 我想要做的是将第2行复制到表格的底部,并将第3行复制到表格的底部2次。同时创建显示品牌的列F

结果应如下所示:

    A        B                          C     D      F
1   Country  Brand                      Model Year
2   France   Peugeot, Citroen (France)  Car   2003   Peugeot
3   France   Peugeot, Citroen (France)  Car   2003   Citroen
4   Germany  VW, Opel, BMW (Germany)    Car   2003   VW
...

另外,我在单独的表格中有品牌列表。

我应该尝试搜索,还是尝试匹配单独表格中列表中的那些品牌?

我是vba的新人,所以任何想法,建议都会受到赞赏!

1 个答案:

答案 0 :(得分:2)

If column B always includes the country from column A in parentheses, consider removing it from the column before performing a split. Something like:

Dim originalWs as Excel.Worksheet, newWs as Excel.Worksheet
Dim countryName as String, allBrands as String, brandArray() as String
Dim rowNumber as long, nextRow as long, i as long

rowNumber = 2 : nextRow = 2

...

countryName = originalWs.Cells(rowNumber,1)
allBrands = originalWs.Cells(rowNumber,2)
brandArray = Split(Replace(allBrands,"(" & countryName & ")",""),",")

...

For i = lbound(brandArray) to ubound(brandArray)
  nextRow = nextRow+1
  With newWs
    .Cells(nextRow,1) = countryName
    .Cells(nextRow,2) = allBrands
    .Cells(nextRow,3) = originalWs.Cells(rowNumber,3)
    .Cells(nextRow,4) = originalWs.Cells(rowNumber,4)
    .Cells(nextRow,5) = brandArray(i)
  End With
Next i

...

The key is that you have to maintain separate counters for:

  • The row in the original worksheet
  • The row being inserted into the new worksheet
  • The brand in the array

Good luck!