2017-06-21 130 views
-2

我製作了用戶表單,因此我將用它來描述我的問題。用戶表單中的算術運算

我想獲得四個用戶輸入(產品成本,銷售單位數量,退貨單位數量和每單位修理費用),並計算6件事情,如總收入(產品成本×銷售單位)和總退貨成本(產品成本×退貨單位數量)。

我該怎麼寫代碼?

用戶窗體的形象在這裏:http://imgur.com/a/qc3Kk

+2

'txtTotalEarnings.Value = txtCostofProduct.Value * txtUnitsSold.Value'等等。請注意,我只是猜測文本框的名稱。你有什麼嘗試? – tigeravatar

+0

@tigeravatar在你對它們進行算術運算之前,你需要將這些字符串轉換成數字。否則,你讓VBA決定,[它可能不會做你想做的事](https://stackoverflow.com/q/44680791/1188513)。 –

回答

0

所以,這是我對這個解決方案。這不是一個非常複雜的程序來創建。總體而言,它是一個UserForm,遵循圖像中的設計,用一段代碼進行計算,一段代碼確保文本框中的值輸入是數字。該接口是標籤和文本框的組合:

enter image description here

有該評估輸入的值是否是NUMERICA並提醒你,如果它是不是每個文本框代碼。每個例程都使用IsNumeric函數用於此目的,並且還可以查看文本框中是否有值。 AfterUpdate事件確保例程只在輸入內容後運行。您可以選擇爲每個文本框分別創建一個例程,或者在每個文本框引用的模塊中編寫更加集成的例程。對於示例的目的:

Private Sub txtCost_AfterUpdate() 

     With UserForm1 
      With .txtCost 

       If Not IsNumeric(.Value) Or .Value = "" Then 
        MsgBox "Please enter a numeric value only!" 
       End If 

      End With 
     End With 

結束子

Private Sub txtReturned_AfterUpdate() 

     With UserForm1 
      With .txtReturned 
       If Not IsNumeric(.Value) Or .Value = "" Then 
        MsgBox "Please ensure you enter only numeric values" 

       End If 

      End With 
     End With 
    End Sub 

    Private Sub txtTotalFix_AfterUpdate() 
     With UserForm1 
      With .txtTotalFix 

       If Not IsNumeric(.Value) Or .Value = "" Then 
        MsgBox "Please ensure you enter only numeric values" 
       End If 

      End With 
     End With 
    End Sub 

    Private Sub txtUnits_AfterUpdate() 

     With UserForm1 
      With .txtUnits 

       If Not IsNumeric(.Value) Or .Value = "" Then 
        MsgBox "Please ensure you enter only numeric values" 
       End If 

      End With 

     End With 
    End Sub 

肉和例程的馬鈴薯也並不複雜。我直接使用每個文本框的值來吐出計算值。另外,你也可以選擇使用變量(我把decalred x As Double,因爲你可能處理的是很大的數字,但在這個例子中沒有使用它)。該例程位於Module1中,並檢查所有值是否都是具有相同IsNumeric函數的數字,並在公式中運行,如果它們中有任何一個爲空或不是數字,則會提示您。我對你是如何計算儲蓄或是否是你的標準並不積極,所以你可能需要調整。

Sub QA_prog() 

Dim x As Double 

With UserForm1 

    If IsNumeric(.txtCost.Value) And IsNumeric(.txtUnits.Value) _ 
     And IsNumeric(.txtReturned.Value) And IsNumeric(.txtTotalFix.Value) Then 

      .lblEarn.Caption = .txtCost.Value * .txtUnits.Value 
      .lblTRC.Caption = .txtCost * .txtTotalFix 
      .lblProfit = .lblEarn.Caption - .lblTRC.Caption 
      .lblCostFix = .txtReturned * .txtTotalFix 
      .lblTE.Caption = .lblProfit - .lblCostFix 
      .lblSave.Caption = .lblTRC + .lblCostFix 

      If .lblSave.Caption > 5000 Then 
       .txtYorN.Text = "NO" 
      Else 
       .txtYorN.Text = "YES" 
      End If 

    Else 

     MsgBox "Double check your values!" 

    End If 

End With 

End Sub 

最後,按鈕。退出按鈕關閉使用卸載程序:

Private Sub cmdExit_Click() 
Unload UserForm1 
End Sub 

計算按鈕調用QA子程序:

Private Sub cmdCalc_Click() 
Module1.QA_prog 
End Sub 

要觸發程序,你只需要一個按鈕添加到電子表格,然後鍵入「UserForm1.show」在其代碼窗口中激活程序。