Excel VBA 每个选定单元格的循环宏
Excel VBA loop macro for each selected cell
我有一个宏,可以简单地更改 selected 行中单元格的值。
Cells(Application.ActiveCell.Row, 20).Select
ActiveCell.Value = "withdraw"
但是我希望能够 select 多行,不一定是连续的,例如 select 下面示例中的 A1、A3 和 A4,并让宏更改列B 对于每个 select 单元格 所以,
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
我如何从 selected 范围中获取活动行并为每一行循环宏?
这里有一个可能的解决方案:
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
请注意,这允许您在任何地方 select 每行任意数量的单元格。
这个简单的代码应该适合你:
Sub Button1_Click()
Dim r As Range
Set r = Selection
r.Offset(, 1) = "Withdraw"
End Sub
我有一个宏,可以简单地更改 selected 行中单元格的值。
Cells(Application.ActiveCell.Row, 20).Select
ActiveCell.Value = "withdraw"
但是我希望能够 select 多行,不一定是连续的,例如 select 下面示例中的 A1、A3 和 A4,并让宏更改列B 对于每个 select 单元格 所以,
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
我如何从 selected 范围中获取活动行并为每一行循环宏?
这里有一个可能的解决方案:
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
请注意,这允许您在任何地方 select 每行任意数量的单元格。
这个简单的代码应该适合你:
Sub Button1_Click()
Dim r As Range
Set r = Selection
r.Offset(, 1) = "Withdraw"
End Sub