![](/img/trans.png)
[英]Excel VBA: Loop and finding multiple values in a range then copying the offset cells in the same range in a categorized list in another worksheet
[英]Excel VBA Loop - Copying cells from one column into another multiple times
這是您可以使用兩個嵌入式循環的方法。
Sub CopyStates()
Dim StateRow%
Dim CopyRow%
Dim FruitRow%
Dim FruitMaxRow%
'these three constants define in which columns your data can be found
Const STATE_COL = 1
Const COPY_COL = 6
Const FRUIT_COL = 7
'these constant define the start row of your data
Const DATA_START_ROW_S = 3 'start row for states
Const DATA_START_ROW_P = 2 'start row for fruits and copy
FruitMaxRow = DATA_START_ROW_P
StateRow = DATA_START_ROW_S
'first, check how many fruits you have
While Cells(FruitMaxRow, FRUIT_COL) <> ""
FruitMaxRow = FruitMaxRow + 1
Wend
'initialize: begin copying at the first empty row where you had fruits
CopyRow = FruitMaxRow
'loop through all the states
While Cells(StateRow, STATE_COL) <> ""
'loop through all the fruits
For FruitRow = DATA_START_ROW_P To FruitMaxRow - 1
'copy the state and fruit
Cells(CopyRow, COPY_COL) = Cells(StateRow, STATE_COL)
Cells(CopyRow, FRUIT_COL) = Cells(FruitRow, FRUIT_COL)
CopyRow = CopyRow + 1
Next FruitRow
StateRow = StateRow + 1
Wend
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.