【问题标题】:Index value for - VBA Excel macro that changes value of cell and runs the model索引值 - 更改单元格值并运行模型的 VBA Excel 宏
【发布时间】:2020-01-17 15:52:45
【问题描述】:

我创建了一个宏来更改名为“选项”的单元格中的值。一旦值发生变化,模型就会发生变化以反映这一点。

例如:

a) Option 1: best case scenario sales -> Cell "option" input 1 
b) Option 2: worst case scenario sales -> Cell "option" input 2
c) etc

然后宏将模型中的结果复制到一个新表中。 因此,对于示例,它将模型的结果从名为“costs”的单元格(它是动态单元格,取决于输出的模型)复制到一个名为“costs_1”的新单元格,该单元格将是静态的。 下面的代码示例。

宏运行良好,但是如果我想输入 100 个选项,那么代码会很长。

有人可以帮助如何在代码中创建一般引用,例如Dim i As Integer i = i + 1,它会一直运行到 100?这会改变单元格名称,例如cost_i 然后是 cost_1, cost_2 cost_3 ... 等等。

非常感谢您的帮助。

最好的问候 一月

Sub RunModel()
' RunModel Macro
....
'Choose Option 1 
Range("option").Select
ActiveCell.FormulaR1C1 = "1"

'Copy costs when option 1 is selected to a new cell
[costs].Select
Selection.Copy
[costs_1].Select
Selection.PasteSpecial Paste:=xlPasteValues

'Copy number of customers when option 1 is selected to a new cell
[customers].Select
Selection.Copy
[customers_1].Select
Selection.PasteSpecial Paste:=xlPasteValues

....
etc
....

'Choose Option 2
Range("option").Select
ActiveCell.FormulaR1C1 = "2"

'Copy costs when option 2 is selected to a new cell
[costs].Select
Selection.Copy
[costs_2].Select
Selection.PasteSpecial Paste:=xlPasteValues

'Copy number of customers when option 2 is selected to a new cell
[customers].Select
Selection.Copy
[customers_2].Select
Selection.PasteSpecial Paste:=xlPasteValues

....
etc
....

【问题讨论】:

    标签: excel vba indexing


    【解决方案1】:
    Sub RunModel()
        dim i as long
        for i = 1 to 100 'Change this to whatever you need it to be
            'No need to select and activate cells or use the clipboard, just copy the values
            range("option").FormulaR1C1 = i
            range("costs_" & i).value = range("costs").value
            range("customers_" & i).value = range("customers").value
            'Do some more stuff
        next i
        'Do some more stuff
    end sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 2017-11-06
      • 2015-10-23
      • 1970-01-01
      • 2018-09-05
      • 2016-12-03
      相关资源
      最近更新 更多