2016-04-21 34 views
0

複製行我需要一些想法如何複製符合標準的行。在標準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

請參閱[如何將2D Excel表「拼合」或「摺疊」爲1D](http://stackoverflow.com/questions/687470)。 – Jeeped

+0

這不是「不透明」的任務。我只想複製那些擁有多個品牌的品牌。我需要複製與'B'列中品牌數量相同的次數 – AK47

+3

查看vba中的Split()函數。然後使用該數組的Ubound來確定是否要複製。您還需要使用Left(Instr())方法去除'()'中的部分。所有這些都是循環遍歷行的循環。併爲分割返回的每個實體分配一個子循環。我會建議在數組中加載所有內容,然後在完成時輸出最終數組。 –

回答

2

如果列B始終在括號中包含來自列A的國家/地區,請考慮在執行拆分之前將其從列中移除。喜歡的東西:

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 

...

的關鍵是,你必須保持獨立的計數器:

  • 在原來的工作表
  • 該行的行插入新工作表
  • 品牌的陣列

祝你好運!