简体   繁体   English

Excel VBA 中的循环——如何在一个范围内迭代一个函数?

[英]Loops in Excel VBA -- How do I iterate a function through a range?

So I know Excel has an NPV function, but I'm trying to make my own since I'm trying to teach myself VBA.所以我知道 Excel 有一个 NPV 函数,但我正在尝试创建自己的函数,因为我正在尝试自学 VBA。 I have data laid out in a table and then I want to iterate through a horizontal range of cells (G5 through I5).我在表格中列出了数据,然后我想遍历单元格的水平范围(G5 到 I5)。 The way I'm trying to structure the loop is by prompting for the number of cash flows and setting that number as the end date.我试图构建循环的方法是提示输入现金流量并将该数字设置为结束日期。 This way the Macro can be used for problems with different durations.这样宏可以用于不同持续时间的问题。

My code is not working and I'm not sure why.我的代码不起作用,我不知道为什么。 Can someone take a look and help me out?有人可以看看并帮助我吗? Please use layman's terms as I just started with VBA yesterday.请使用外行的术语,因为我昨天刚开始使用 VBA。

Sub NPV()
Dim y As Integer, inv As Double, tax As Double, sal As Double, wc As Double, dr As Double, i As Integer, v As Double
y = Range("C4")
inv = Range("C5")
tax = Range("C6")
sal = Range("E4")
wc = Range("E5")
dr = Range("E6")

Dim total As Double
total = 0
For i = 1 To y
    v = Range("5, 5 + i")
    v = v / (1 + dr) ^ i
    total = total + v
    Next i

total = total + ((1 - tax) * sal) + wc
Range("F5").Value = total
End Sub

Consider replacing:考虑更换:

v = Range("5, 5 + i")

with:和:

v = Cells(5, 5 + i)

暂无
暂无

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

相关问题 如何按我排序的顺序遍历VBA中的Excel排序范围? - How do I Loop Through A Sorted Excel Range in VBA in the Order I Sorted It In? 如何在循环显示一系列单元格时获取当前单元格编号(Excel VBA) - How do I get the current cell number whilst looping through a range of cells (Excel VBA) 如何在VBA的单元格范围内搜索excel,以获取不等于“短语”的字符串值 - How do I search through a Range of cells in VBA for excel for values that are a strings not equal to “phrase” Excel VBA:有没有办法遍历特定范围内的字符? - Excel VBA: Is there a way to iterate through characters in a specific range? 如何使用VBA在Excel中迭代可变列长度范围 - How to iterate through a variable-column-length range in Excel using VBA 如何创建一组用户选择的单元格,我可以从中在 Excel vba 中迭代? - How do I create a selection set of user picked cells from which I can iterate through in Excel vba? 在Excel VBA中,如何更改作为用户输入传递给函数的单元格区域 - In Excel VBA, How do I change the cell range that was passed as a user input to a function 如何使用Excel VBA中的模块功能将值设置为范围? - how do i set a value to a range using a function from module in excel vba? 如何在Excel VBA中编写一个采用参数范围或参数列表的函数? - How do I write a function that takes a range or list of arguments in Excel VBA? 如何使用 epplus 遍历 excel 表中的行? - How do I iterate through rows in an excel table using epplus?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM