简体   繁体   English

Excel VBA-通过另一个单元格更改单元格值?

[英]Excel VBA - Change cell value via another cell?

So VBA is completely new to me. 所以VBA对我来说是全新的。 I come from a C# background. 我来自C#背景。 Currently creating an order form, whereby I can input the total amount I require of an object and then the price is calculated in a different cell. 当前正在创建一个订单,我可以输入一个对象所需的总金额,然后在另一个单元格中计算价格。

However I also want the price to change based off amount thresholds for that object. 但是,我也希望价格根据该对象的金额阈值进行更改。

Say for example 0 - 100 will cost £2.50 so I expect the answer to be anywhere within that range is multiplied by 2.50. 假设0-100的费用为£2.50,因此我希望答案在该范围内的任何地方都乘以2.50。 Meanwhile if the amount exceeds 100 and becomes 120 I want the object price to now reflect £2.30 and proceed to multiple the 120 by £2.30. 同时,如果金额超过100并变为120,我希望对象价格现在反映2.30英镑,然后将120乘以2.30英镑。

I've noticed a few tutorials on line but they don't exactly explain how I might be able to achieve the above. 我注意到在线上有一些教程,但是它们并没有完全解释我如何能够实现上述目标。 Wondering if anyone can point me in the right direction? 想知道是否有人可以指出我正确的方向?

Non VBA Soluion 非VBA解决方案

If you build a table with the bottom and upper thresholds for a price, you can simply use a VLOOKUP and return the approximate match. 如果您使用价格的最低和最高阈值构建表,则可以简单地使用VLOOKUP并返回近似匹配。

In photo, Column C is the output from the equation that is shown in Column D 在照片中, Column C Column D所示方程的输出

在此处输入图片说明


VBA Solution VBA解决方案

You can also use a simple UDF . 您也可以使用简单的UDF Paste the code inside a Module and then you can call the function PRICEINDX from a cell just like any other equation. 将代码粘贴到Module ,然后就可以像其他方程式一样从单元格中调用函数PRICEINDX You can either manually type in a value like PRICEINDX(164) or select a cell that has the value to be tested like PRICEINDX(A1) 您可以手动输入PRICEINDX(164)之类的值,也可以选择具有要测试的值的单元格,例如PRICEINDX(A1)

You can also set up more complex thresholds easily by using Select Case 您还可以使用Select Case轻松设置更复杂的阈值

Option Explicit

Public Function PRICEINDX(Target As Double) As Double

Dim ans As Double

Select Case Target
    Case 0 To 100
        ans = 2.5
    Case 101 To 200
        ans = 2.3
    Case 201 To 300
        ans = 2.1
    Case Is > 300
        ans = 2
End Select

PRICEINDX = ans

End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM