简体   繁体   English

VBA - Excel 通过一列中每一行的宏

[英]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.我正在开发一种工具,它可以让我调用大约 15 个潜艇从一个单元格中获取文本,分析它,然后为它生成一个字母。 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.我需要弄清楚的另一件事是,它使用正在运行宏的单元格的内容作为标题保存 PDF,如果保存 PDF 宏在循环内,我怎么能让它引用单元格。 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.你说你想从你引用的每个单元格中获取文本,并在你的 15 个其他过程中使用它。

As @BigBen said - you need to reference the start and end cell of your range.正如@BigBen 所说-您需要引用范围的开始和结束单元格。 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.此代码将 go 通过范围内的每个单元格并将其传递给宏。 It also demonstrates the With...End With code block which helps simplify the code syntax.它还演示了有助于简化代码语法的With...End With代码块。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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