首页 > 解决方案 > 如何在Excel中的n个单元格中保持恒定的值并在结束后通过添加固定数字来更改它

问题描述

我想在 excel 的 4 个单元格中保持一个值不变,然后通过添加一个固定值来更改它,并为另外 4 个单元格保持新值不变。在以下代码中,您可以看到所需的结果。

Starting value:            
3

Fixed value:
5
Number of iterations:
4

Table that I want to create:
3
3
3
3
8
8
8
8
13
13
13
13

到目前为止,我已成功在所需单元格中重复给定值,如下所示:

Values
1
2
3

Table
1
1
1
1
2
2
2
2
3
3
3

通过实现以下excel函数:

=OFFSET($A$1,MOD(FLOOR((ROW()-1)/5,1),COUNTA($A:$A)),0)

标签: excelexcel-formula

解决方案


作为用户定义函数的一个选项:我假设您几乎没有先验知识,但您知道如何创建宏。如果没有,请看这里例如:https://www.tutorialspoint.com/excel_macros/excel_creating_a_macro_using_vba_editor.htm t 如果您想在 VBA 中执行此操作,那么您可以创建一个用户定义的函数,将您的 3 个变量作为其输入(staring_value, fixed_value, number_of_iterations) 并返回一个值数组。

Option Explicit
Public Function calculate_output(ByVal starting_value As Double, _
                                  ByVal fixed_value As Double, _
                                  ByVal number_of_iterations As Integer, _
                                  Optional ByVal number_of_levels As Variant) As Variant()

  If IsMissing(number_of_levels) Then number_of_levels = 3

  Dim result() As Variant
  ReDim result(starting_value * number_of_iterations - 1, 0)
  
  Dim i As Integer
  Dim j As Integer
  
  For j = 1 To number_of_levels
    
    For i = 1 To number_of_iterations

      result(i + (j - 1) * number_of_iterations - 1, 0) = starting_value + (j - 1) * fixed_value

    Next i
  
  Next j
  
  calculate_output = result

End Function

推荐阅读