2015-11-01 28 views
0

我會開始說我有一個星期前開始教自己的VBA,所以我可能不會問正確的問題,但...在Word VBA中增加0.05的小數點

我是試圖在Word VBA中編寫一個循環,該循環將增加從書籤檢索的文本中部分計算的數字。我希望它湊到最接近的0.05,所以.87變成0.90和0.21變成0.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 

現在假設用於書籤「SRebateIncome」,「RebateDefault」和「TRebateIncome」的值輸入是10175,1602和43046分別我期望的輸出爲1460.80,但是「K」返回爲1460.78。

在這個階段,我不知道在Word中使用Excel的任何內容(除了複製/粘貼到文檔的電子表格,我不想這樣做)。

任何幫助,將不勝感激

謝謝!

+0

乘以20,舍入到最接近的整數,然後除以20。 –

回答

0

您可以使用Excel對象和吊頂功能

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 

希望這有助於做到這一點。 :)

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