我想使用VBA在单元格上插入计算。这是我现在插入的方式。它的工作相当不错,但是我不能修改发票表上的百分比。我希望在插入行后可以修改百分比,它会自动更新售价。

Private Sub CommandButton1_Click()
Dim wsInvoice As Worksheet, wsRange As Worksheet, wsPrice As Worksheet
Dim nr As Integer, lr As Integer
With ThisWorkbook
     Set wsInvoice = .Worksheets("Invoice")
     Set wsRange = .Worksheets("Range")
     Set wsPrice = .Worksheets("Price")
 End With
nr = wsInvoice.Cells(Rows.Count, 1).End(xlUp).Row + 1
Select Case Me.ComboBox1
Case "Paper"
    wsRange.Range("Paper").Copy wsInvoice.Cells(nr, 1)
    lr = wsInvoice.Cells(Rows.Count, 1).End(xlUp).Row
    For i = nr To lr
        wsInvoice.Cells(i, 2) = Application.VLookup(Cells(i, 1), wsPrice.Range("A:B"), 2, 0)
        wsInvoice.Cells(i, 3) = (".3")
        wsInvoice.Cells(i, 4).Formula = FormatCurrency(wsInvoice.Cells(i, 2).Value / (1 - (wsInvoice.Cells(i, 3))), 2, vbFalse, vbFalse, vbTrue)
    Next i


这是下载我的文档的链接。
https://drive.google.com/file/d/0By_oZy042nKWdTVmX0Fid3JVSHM/edit?usp=sharing

最佳答案

我认为这里的FormatCurrency没什么用,可以通过格式化该列一次并像这样保留它来完成。窗体函数内部的Formula和FormulaLocal似乎存在问题。这是我的解决方法:

删除wsInvoice.Cells(i,4).Formula ...

在CommandButton1_Click()的末尾,添加此行FormulaCorrection

在模块内部,记下这个非常简单的函数,它将执行您想要的操作:

Sub FormulaCorrection()

    Sheets("Invoice").Activate
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    For x = 2 To lastRow
        Cells(x, 4).FormulaLocal = "=B" & x & "/(1-C" & x & ")"
    Next x

End Sub

08-26 11:04