简体   繁体   中英

VBA - Excel through macros for each row in a column

I am working on developing a tool that would allow me to call about 15 subs to take text from a cell, analyze it, and then generate a letter for it. Now I haven't worked with loops much but I wanted to see if my thinking on this is right or if there is advice on how to make it better:

    Sub Loop_Process()
Dim myrange as string
myrange = Cells(Rows.Count, 1).End(xlUp).Address

For each i in Range(myrange).Rows
Call Macro 1
Call Macro 2
'etc

Next i
End sub

Would that work to funnel through the whole list? Any major pitfalls that you can think of? The other thing I need to figure out is that it saves PDFs with the contents of the Cell it is running the macro on as the title, If the save PDF macro is within the Loop, how could I get it to reference the cell. Does that make sense? Thank you for the help

You say you want to take text from each cell you reference and use it within your 15 other procedures.

As @BigBen said - you need to reference the start and end cell of your range. At the moment you're just looking at the last cell.

This code will go through each cell in the range and pass it to a macro. It also demonstrates the With...End With code block which helps simplify the code syntax.

Public Sub Test()

    Dim myRange As Range
    
    'Always be specific which workbook and sheet your range is on.
    'The overall range and the start/end cells are fully qualified:
    'Set myRange = ThisWorkbook.Worksheets("Sheet1").Range( _
    '                 ThisWorkbook.Worksheets("Sheet1").Cells(1, 1), _
    '                 ThisWorkbook.Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp))
                  
    'The above row shortened using the With...End With block.
    With ThisWorkbook.Worksheets("Sheet1")
        Set myRange = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
    End With
    
    Dim myCell As Range
    For Each myCell In myRange.Cells
        Macro1 myCell 'Pass the cell reference to the Macro1 procedure.
    Next myCell
    
End Sub

Public Sub Macro1(CellRef As Range)

    With CellRef
        MsgBox "Row:  " & .Row & vbCr & _
               "Col:" & Split(.Address, "$")(1) & vbCr & _
               "Val: " & .Value
    End With

End Sub

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