在Word VBA

时间:2015-11-01 22:38:18

标签: vba word-vba

我开始说我一周前开始教自己VBA,所以我可能不会问正确的问题,但是......

我正在尝试在Word VBA中编写一个循环,该循环将增加从书签中检索的文本部分计算的数字。我希望它向上舍入到最近的.05,所以.87变为.90而.21变为.25。

我写的模块如下:

A = ActiveDocument.Bookmarks("SRebateIncome").Range.Text
B = ActiveDocument.Bookmarks("RebateDefault").Range.Text
C = ((A - 6000) * 0.15)
D = B - C
E = B + D
F = (18200 + ((445 + E) / 0.19)) + 1
G = (0.19 * 18200) + 445 + E + (37000 * (0.015 + 0.325 - 0.19))
H = (G / (0.015 + 0.325)) + 1
I = ActiveDocument.Bookmarks("TRebateIncome").Range.Text

If F < 37000 = True Then
    J = (0.125 * (I - F))
Else
    J = (0.125 * (I - H))
End If

K = E - J
K = Format(Round(K, 2), "###,##0.00")
'round K up to the nearest .00 or .05
If K <> "###,###.#0" = False or K <> "###,###.#5") = False Then
    Do
        K = K + 0.01
    Loop Until K = "###,###.#0" = True or K <> "###,###.#5") = True
End If

Set RebateOutput = ActiveDocument.Bookmarks("RebateOutput").Range
RebateOutput.Text = K

现在假设书签的输入值为&#34; SRebateIncome&#34;,&#34; RebateDefault&#34;和&#34; TRebate收入&#34;分别是10175,1602和43046,我预计输出为1460.80,而是&#34; K&#34;返回为1460.78。

在这个阶段,我对单词中使用Excel一无所知(除了将电子表格复制/粘贴到文档中,我不想这样做)。

任何帮助将不胜感激

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用excel对象和Ceiling函数

来完成
Option Explicit

Sub RoundText()

    Dim dblSRebateIncome As Double
    Dim dblRebateDefault As Double
    Dim dblTRebateIncome As Double
    Dim dblFinal As Double
    Dim rngOutput As Range
    Dim oExcel As Object

    ' Load the variables
    Set oExcel = CreateObject("Excel.Application")
    Set rngOutput = ActiveDocument.Bookmarks("RebateOutput").Range
    dblSRebateIncome = CDbl(ActiveDocument.Bookmarks("SRebateIncome").Range.Text)
    dblRebateDefault = CDbl(ActiveDocument.Bookmarks("RebateDefault").Range.Text)
    dblSRebateIncome = CDbl(ActiveDocument.Bookmarks("TRebateIncome").Range.Text)

    dblFinal = GetCalculatedValue(dblSRebateIncome, dblRebateDefault, dblTRebateIncome)

    dblFinal = oExcel.worksheetfunction.Ceiling(dblFinal, 0.05)

    rngOutput.Text = Format$(dblFinal, "###,##0.00")

End Sub

Function GetCalculatedValue(ByVal dblSIncome As Double, _
                            ByVal dblDefault As Double, _
                            ByVal dblTIncome) As Double

    ' Declare all the intermediate variables.
    Dim c As Double, d As Double, e As Double
    Dim f As Double, g As Double, h As Double
    Dim j As Double, ret As Double

    ' Perform the complicated calculation
    c = ((dblSIncome - 6000) * 0.15)
    d = dblDefault - c
    e = dblDefault + d
    f = (18200 + ((445 + e) / 0.19)) + 1
    g = (0.19 * 18200) + 445 + e + (37000 * (0.015 + 0.325 - 0.19))
    h = (g / (0.015 + 0.325)) + 1

    If f < 37000 Then
        j = (0.125 * (dblTIncome - f))
    Else
        j = (0.125 * (dblTIncome - h))
    End If

    ret = e - j


    ' Return the value of the fucntion
    GetCalculatedValue = ret

End Function

希望这会有所帮助。 :)

答案 1 :(得分:0)

Dim x As Double
x = 1.111 'E.g.
Debug.Print Round(x * 20, 0)/20 '>> 1.10