Word文档中的发票

时间:2017-07-25 10:24:02

标签: vba excel-vba ms-word word-vba excel

我正在尝试编写一个VBA脚本,以乘以ms中存在于表中的数字。

到目前为止,我已设法执行以下操作,但b的值在文档中显示为11,000英镑,当我发出消息时,它总是将其返回为0.

我想将b的值设为11000,这样我就可以倍增,任何想法或已编写的代码都会很棒。

Private Sub Calculate_Click()

    Dim t1 As Table
    Dim a As Double
    Dim m, b As Currency

    ' first table
    Set t1 = ActiveDocument.Tables(1)

    a = Val(t1.Cell(5, 3).Range.Text)
    a = a/100

    b = Val(t1.Cell(7, 4).Range.Text)
    'b = CCur(t1.Cell(7, 4).Range.Text)   **I tried this but didn't work
    MsgBox b

    m = a * b
    t1.Cell(5, 4).Range.Text = Format(m, "Currency")

 End Sub

2 个答案:

答案 0 :(得分:0)

你的代码很完美 - 直到你试图把锦上添花。 :-) Dim a As Double, b As Double这是因为你不想将苹果与橘子相乘。 m = a * b给出正确的结果,但转换为货币,基本上除以100.但也许这是在这一行t1.Cell(5, 4).range.Text = Format(m, "Currency")中完成的。我不知道。 我建议声明m As Double并将结果格式化为Format(m, "#,##0.00")

以下是完整的建议代码。

Private Sub Calculate_Click()

    Dim a As Double, b As Double, m As Double
    Dim Ccy As String

    With ActiveDocument.Tables(1)             ' first table
        a = CellValue(.Cell(5, 3))
        b = CellValue(.Cell(7, 4), Ccy)
        m = a * b / 100
        If Ccy = "" Then Ccy = ChrW(163)
        If Len(Ccy) > 1 Then Ccy = Ccy & " "
        .Cell(5, 4).range.Text = Format(m, Ccy & "#,##0.00")
'        .Cell(5, 4).range.Text = Format(m, "Currency")
    End With
End Sub

Private Function CellValue(Target As Cell, _
                           Optional Ccy As String) As Double

    Dim Numbers As String
    Dim Txt As String, Ch As String
    Dim i As Long, n As Long

    Txt = Replace(Trim(Target.range.Text), Chr(13), "")
    n = Len(Txt)
    Do While i < n
        i = i + 1
        Ch = Mid(Txt, i, 1)
        If IsNumeric(Ch) Then Exit Do
    Loop
    If i Then Ccy = Trim(Left(Txt, i - 1))

    Txt = Mid(Txt, i)
    n = Len(Txt)
    For i = 1 To n
        Ch = Mid(Txt, i, 1)
        If IsNumeric(Ch) Or (Ch = ".") Then Numbers = Numbers & Ch
    Next i
    CellValue = Val(Numbers)
End Function

ChrW(163)是£符号。我已将其添加到输出的数字格式中。使用此行或“货币”作为格式的行之间的区别在于“货币”格式在“区域设置”中定义,而另一行定义它在您看到的位置。

函数CellValue将获取价格单元格中使用的货币并将其应用于整个单元格。如果货币是多字符缩写(如GBP),则会添加一个空格。如果没有给出货币,将使用£,没有空格。

答案 1 :(得分:0)

实际上这是一个有趣的问题。一般来说,如果你想将70066欧元和52美分乘以10,这就是它的样子:

enter image description here

在我的设置中,我使用,作为小数点分隔符,使用.作为千位分隔符。因此,我将,替换为.,我忽略了.。像这样:

Replace(Replace(.Cell(1, 1).Range.Text, ".", ""), ",", ".")

整个代码如下所示:

Option Explicit

Private Sub TestMe()

    Dim t1  As Table
    Dim a   As Currency
    Dim m   As Currency
    Dim b   As Currency

    Set t1 = ActiveDocument.Tables(1)

    With t1
        a = Val(Replace(Replace(.Cell(1, 1).Range.Text, ".", ""), ",", "."))
        b = Val(Replace(Replace(.Cell(1, 2).Range.Text, ".", ""), ",", "."))
        m = a * b
        .Cell(2, 1).Range.Text = Format(m, "Currency")
    End With

End Sub

它将70066,52欧元乘以10,并返回700665,20欧元。