簡體   English   中英

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

[英]VBA - Excel through macros for each row in a column

我正在開發一種工具,它可以讓我調用大約 15 個潛艇從一個單元格中獲取文本,分析它,然后為它生成一個字母。 現在我沒有過多地使用循環,但我想看看我對此的想法是否正確,或者是否有關於如何使它變得更好的建議:

    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

這會影響整個列表嗎? 您能想到的任何主要陷阱? 我需要弄清楚的另一件事是,它使用正在運行宏的單元格的內容作為標題保存 PDF,如果保存 PDF 宏在循環內,我怎么能讓它引用單元格。 那有意義嗎? 感謝您的幫助

你說你想從你引用的每個單元格中獲取文本,並在你的 15 個其他過程中使用它。

正如@BigBen 所說-您需要引用范圍的開始和結束單元格。 目前你只是在看最后一個單元格。

此代碼將 go 通過范圍內的每個單元格並將其傳遞給宏。 它還演示了有助於簡化代碼語法的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