按标题选择一列,然后使用宏将其舍入到最接近的美分

时间:2018-09-04 16:49:54

标签: excel vba

我需要使用宏四舍五入到最接近的一分钱。我已经通过当前设置的宏获得了“ Round”功能(请参见下面的代码),以显示一个弹出窗口,供用户手动选择要取整的数据。

但是,我想让宏自动选择标题为“费用率”的列的整个数据填充范围(仅在填充数据的地方-这将是不同的列,并且每次行的行长不同)并应用ROUND函数:ROUND(DATA,2)

Dim Rng As Range
Dim WorkRng As Range
Dim xNum As Integer
On Error Resume Next
xTitleId = "ROUND Formula"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Use Mouse to select entire FEE RATE column, then click on OK", xTitleId, WorkRng.Address, Type:=8)
For Each Rng In WorkRng
Rng.Value = Application.WorksheetFunction.Round(Rng.Value, 2)
Next

1 个答案:

答案 0 :(得分:0)

这是一种方法,使用“查找”查找标头(假设它在第1行中),然后假设范围是一直向下的下一个单元格。如果您只有一个条目,则可能需要从底部开始。

您也可以使用“评估”来避免循环,尽管这可能会带来边际收益。

Sub x()

Dim rFind As Range
Dim Rng As Range
Dim WorkRng As Range

Set rFind = Rows(1).Find(What:="FEE RATE", Lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind Is Nothing Then
    Set WorkRng = Range(rFind.Offset(1), rFind.End(xlDown))
    'For Each Rng In WorkRng
    '    Rng.Value = Application.WorksheetFunction.Round(Rng.Value, 2)
    'Next
    WorkRng = Evaluate("IF(" & WorkRng.Address & "="""","""",ROUND(" & WorkRng.Address & ",2))")
End If

End Sub