每个选定单元格的Excel VBA循环宏

时间:2015-01-26 15:02:52

标签: excel vba excel-vba

我有一个宏,它只是更改所选行中单元格的值。

Cells(Application.ActiveCell.Row, 20).Select
ActiveCell.Value = "withdraw"

但是我希望能够选择多个行,不一定是连续的,例如,从以下示例中选择A1,A3和A4,并为每个选择单元格更改宏B,

    A        B  
1 Brian
2 James
3 Jenny
4 Frank
5 Tim

变为

    A        B  
1 Brian   Withdraw
2 James
3 Jenny   Withdraw
4 Frank   Withdraw
5 Tim

我如何从所选范围中获取活动行并为每行循环宏?

2 个答案:

答案 0 :(得分:1)

这是一个可能的解决方案:

Private Sub a()
    Dim sSel As String
    Dim aSel As Variant
    Dim rX As Range
    Dim i As Integer
    Dim j As Integer

    sSel = Selection.Address
    aSel = Split(sSel, ",")
    For i = 0 To UBound(aSel)
        Set rX = Application.ActiveCell.Parent.Range(CStr(aSel(i)))
        For j = 1 To rX.Rows.Count
            rX.Rows(j).EntireRow.Cells(1, 2) = "withdraw"
        Next
    Next
End Sub

请注意,这样您就可以选择每行的任意位置和任意数量的单元格。

答案 1 :(得分:0)

这个简单的代码应该适合你:

Sub Button1_Click()
    Dim r As Range
    Set r = Selection
    r.Offset(, 1) = "Withdraw"
End Sub