簡體   English   中英

Excel VBA 循環 - 將單元格從一列復制到另一列多次

[英]Excel VBA Loop - Copying cells from one column into another multiple times

我正在嘗試創建一個循環來提取第二張圖像上的值。

圖 1 - 文件1 圖 2 - 循環結束結果

這是您可以使用兩個嵌入式循環的方法。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM