简体   繁体   中英

creating a loop in vba for an excel macro

I have recorded a macro in Excel that takes data from certain cells in one page of a spreadsheet and copies them to page in a different order. it does each cell individually, and is quite long.

However it only does it for one row of data in the first page.

How do I make this single macro into a loop that copies the same data but from each row into the new page?

I haven't included the macro code since it is very long but can do so if necessary.

Thanks

You could omit your code to only show the relevant part, or code a mockup macro to address only and only your problem.

Lets imagine your problem as a sub, which in this case is highly omitted:

Sub OmittedSub()
    ' Do stuff
End Sub

You can create new sub to call it many times, this new sub would be the one you would be calling instead:

Sub LoopOmittedSubs()
    Dim i As Integer

    ' Loop to call your macro routine multiple times
    For i = 1 To 100
        OmittedSub
    Next
End Sub

In case you would need to pass a value, for example your macro does not know which row to affect and you would need to tell it, you can pass the loop variable like this:

Sub OmittedSub(iRow As Integer)
    ' Do stuff for row number iRow
End Sub

Sub LoopOmittedSubs()
    Dim i As Integer

    ' Loop to call your macro routine multiple times
    For i = 1 To 100
        OmittedSub i
    Next
End Sub

This answer is the very basics of VBA. I dont know how to answer your question better without knowing what you already tried, how you tried, etc...

Raybarg provided you basic solution to that problem. I am not sure what do you mean by "certain cell", does it mean they have certain value or there are in regular order like A5, A10, A15?

In both cases you probably will use Raybarg's code and conditional statements.

You should include your code, it gives some hints on what you actually want to achieve and where is error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM