从定义的范围转换excel宏,只对选定的单元格进行操作?
Posted
技术标签:
【中文标题】从定义的范围转换excel宏,只对选定的单元格进行操作?【英文标题】:Convert excel macro from defined range, to operate on selected cells only? 【发布时间】:2019-08-27 01:08:46 【问题描述】:我有一个宏可以做我想做的事,但它在一组单元格上运行。我一直试图让它只在用户选择(突出显示)的单元格上运行。我尝试了使用 Dim Rng 作为 Range 以及 Selection 方法来定义范围的各种组合。我:没有VBA经验可言,一些python经验。
工作代码(定义范围)
Sub NoHalve()
'
' Macro to remove less-than sign and report only the LOR formatted grey and underlined .
' x = columns, y = rows
For x = 1 To 200
For y = 2 To 3000
If Left(Cells(y, x), 1) = "<" Then
Cells(y, x) = (Right(Cells(y, x), Len(Cells(y, x)) - 1))
Cells(y, x).Select
Selection.Font.ColorIndex = 16
Selection.Font.Underline = xlUnderlineStyleSingle
End If
Next y
Next x
End Sub
这是我尝试让它在用户选择的单元格上运行,这给了我 r.Select 行的对象所需的错误:
Sub NoHalve_selection()
Set Rng = Selection
For Each r In Rng
If Left(r, 1) = "<" Then
r = (Right(r, Len(r) - 1))
r.Select
Selection.Font.ColorIndex = 16
Selection.Font.Underline = xlUnderlineStyleSingle
End If
Next
End Sub
【问题讨论】:
这可能是Application.InputBox
选择范围的候选对象。
不需要遍历选择中的每个单元格。您可以使用.Find
和.FindNext
来循环仅看起来像“
也可以把Cells(y, x) = (Right(Cells(y, x), Len(Cells(y, x)) - 1))
写成Cells(y, x) = Mid(Right(Cells(y, x),2)
【参考方案1】:
你快到了
Sub NoHalve_selection()
Dim r As Range, Rng As Range
Set Rng = Selection
For Each r In Rng.Cells ' .Cells is implied in For Each r in Rng
With r 'Using With block is more efficient as it does fewer lookups to Excel
If Left$(.Value, 1) = "<" Then ' .Value uses the With block (so is the same as r.Value). Value is the default property of a Range
.Value = Mid$(.Value, 2)
.Font.ColorIndex = 16
.Font.Underline = xlUnderlineStyleSingle
End If
End With
Next
End Sub
原帖对比
Sub NoHalve_selection()
Dim r As Range, Rng As Range
Set Rng = Selection
For Each r In Rng
If Left(r, 1) = "<" Then
r = (Right(r, Len(r) - 1))
r.Font.ColorIndex = 16
r.Font.Underline = xlUnderlineStyleSingle
End If
Next
End Sub
【讨论】:
【参考方案2】:通过将硬编码数字替换为Selection.Columns.Count
和Selection.Rows.Count
,这应该相对容易。
Sub NoHalve()
'
' Macro to remove less-than sign and report only the LOR formatted grey and underlined .
' x = columns, y = rows
For x = 1 To Selection.Columns.Count
For y = 2 To Selection.Rows.Count
If Left(Cells(y, x), 1) = "<" Then
Cells(y, x) = (Right(Cells(y, x), Len(Cells(y, x)) - 1))
Cells(y, x).Font.ColorIndex = 16
Cells(y, x).Font.Underline = xlUnderlineStyleSingle
End If
Next y
Next x
End Sub
如果您要进行简单的文本替换(删除符号),只要该符号在最左边,那么我还建议您使用不太依赖字符串中字符位置的东西.所以像replace
:
Cells(y, x) = replace(Cells(y, x),"<","",,1)
另外我不认为Cells(y, x).Select
行是必需的,并且可能会不必要地更改活动选择。
【讨论】:
如果您将.select
留在其中,您将在第二次迭代中放弃所有内容
在内部位上,您可以将selection.
替换为cells(y,x).
,因为如果保持selection
,它将适用于整个更大的组,而不仅仅是您要更改的单元格以上是关于从定义的范围转换excel宏,只对选定的单元格进行操作?的主要内容,如果未能解决你的问题,请参考以下文章