VBA Excel:扩展和缩短单元格范围
根据select哪个选项button,将不同的数组加载到一个单元格范围内(请参见下面的示例)。 我想通过旋转button添加扩展和缩小单元格范围(以及数组)的function。 我将如何去做呢?
基本上我问:是否有一种方法可以添加另一个元素到这个数组中,并反映在正在使用的单元格区域中?
附加:有一个图表表示这个单元格的范围,我将如何使该图表的系列dynamic? (随着范围增加/减less)
Private Sub OptionButton4_Click() With Application .ScreenUpdating = False End With Dim rng As Range Dim cell As Range Dim counter As Long OptionButton4.Height = 26.25 OptionButton4.Width = 87 OptionButton4.Left = 330.75 OptionButton4.Top = 408 Set rng = Range("B2", "AF2") counter = 0 pwmArray(0) = "0" pwmArray(1) = "10" pwmArray(2) = "0" pwmArray(3) = "10" pwmArray(4) = "10" pwmArray(5) = "0" pwmArray(6) = "10" pwmArray(7) = "10" pwmArray(8) = "10" pwmArray(9) = "0" pwmArray(10) = "10" pwmArray(11) = "10" pwmArray(12) = "10" pwmArray(13) = "10" pwmArray(14) = "0" pwmArray(15) = "10" pwmArray(16) = "10" pwmArray(17) = "10" pwmArray(18) = "10" pwmArray(19) = "10" pwmArray(20) = "0" pwmArray(21) = "10" pwmArray(22) = "10" pwmArray(23) = "10" pwmArray(24) = "10" pwmArray(25) = "10" pwmArray(26) = "10" pwmArray(27) = "0" pwmArray(28) = "0" pwmArray(29) = "0" pwmArray(30) = "0" If OptionButton4.Value = True Then For Each cell In rng cell.Value = pwmArray(counter) counter = counter + 1 Next cell End If With Application .ScreenUpdating = True End With End Sub
从你发布的代码看来,你正在使用一个静态数组。 你需要一个dynamic数组。 Chip Pearson 在数组上写了很多。 我鼓励你检查一下。
所以对于这种情况,你会想要做这样的事情:
Option Base 1 '<~~ This sets the lower bound to 1 instead of the default 0 Sub Main() Dim pwmArray() As Long ReDim pwmArray(1 To 31) 'Fill your array with values here 'Now if an element needs to be added to the array (and you want to keep _ ' the current values) do the following: ReDim Preserve pwmArray(1 To 32) pwmArray(32) = x End Sub
请注意Preserve
关键字。 这将保持数组中的值,同时只增加最后一个维度的大小。
现在, ReDim
声明是性能饥饿的,所以我通常只在代码中尝试一次ReDim
如果可能的话,将ReDim
保留在循环之外)。
未经testing!
但是为了决定这个范围,你可以做这样的事情
i = InputBox("Range") Set Rng = Range(Cells(1, 2), Cells(i, 2))
然后,这个列将被设置为他们input的数字,所以如果他们input3,就等于A2:C2。
至于旋转button,我不知道如何整合,但至less给你一个开始。