如何在列中每 n 行在两个值之间交替

How to alternate between two value every nth row in a column

提问人:JLit98 提问时间:11/7/2023 更新时间:11/7/2023 访问量:28

问:

我想从第 2 行开始输入“深色”和“浅色”,其中输入 2 行的“深色”,然后输入 2 行的“浅色”,依此类推,直到“A”列的最后一行

它应该是什么样子的示例

A  Phase
1  "Dark"
2  "Dark"
3  "Light"
4  "Light"
5  "Dark"
6  "Dark"
... ...

我在下面尝试了这段代码,但每 12 行重复一次“深色”和“浅色”并从第 3 行开始在每个值之间交替是非常不一致的

Sub light_dark()
Dim dws As Worksheet
Dim lr As Long
Dim i As Integer, j As Integer
Dim value As String

Set dws = ThisWorkbook.Worksheets("Data")
lr = dws.Range("A" & dws.Rows.Count).End(xlUp).Row

dws.Range("B:B").EntireColumn.Insert
dws.Range("B1").Value2 = "Phase"
dws.Range("B2").Value2 = "Light"


For i = 3 To lr 'row index
    j = (i - 1) Mod 25 '0 to 12 hours count
    If j < 14 Then
        value = "Dark"
    Else
        value = "Light"
    End If
    dws.Cells(i, 2).value = value
Next i

End Sub
Excel VBA

评论

0赞 FaneDuru 11/7/2023
“它应该是什么样子的例子”除了让我们感到困惑之外,还有意义吗?您是否尝试(在代码中)放置 12 行“Dark”,然后是其他 12 行“Light”?如果没有,请(用文字)解释你到底要完成什么。

答:

2赞 FunThomas 11/7/2023 #1

您的代码(使用 )的基本思想是可以的,但有一些细节。Mod

如果你想让相同的字符串乘以另一个,那么你需要使用(在你的例子中,n=2 和 2*n=4)。using 将返回 0、1、2 或 3。值 0 和 1 () 代表第一个字符串 (=),值 2 和 3 () 代表第二个字符串。nnMod 2*nMod 4< ndark>= n

您应该从值 0 开始计算,因此从 中减去起始行(在本例中为 3)。i

Const n = 2
Const startRow = 3
For i = startRow To lr 'row index
   j = (i - startRow) Mod (n * 2)
   dws.Cells(i, 2).Value = IIf(j < n, "Dark", "Light")
Next i

或者在 B 列中使用与公式类似的逻辑:

=IF(MOD(A3-1;4)<2, "Dark", "Light")
1赞 FaneDuru 11/7/2023 #2

请以另一种方式进行测试。即使是非常大的范围,它也应该非常快。它在内存中工作,在代码末尾加载数组并立即删除处理后的结果:arr

Sub light_dark()
 Dim dws As Worksheet, lr As Long, i As Long, j As Long
 Dim boolDark As Boolean, arr
 Const C1 As String = "Dark", C2 As String = "Light", repNo As Long = 12 'rows to repeat (you can play with it...) 

 Set dws = ActiveSheet ' ThisWorkbook.Worksheets("Data")
 lr = dws.Range("A" & dws.rows.count).End(xlUp).Row
 
 dws.Range("B:B").EntireColumn.insert
 dws.Range("B1").Value2 = "Phase"
 dws.Range("B2").Value2 = "Light"
 
 ReDim arr(1 To lr - 2, 1 To 1) 'redim the array to keep processed result
 boolDark = True 'initialize the boolean variable to start with Dark
 
 For i = 1 To UBound(arr) Step repNo
        For j = 1 To repNo
            If i + j - 1 > UBound(arr) Then Exit For  'when the array last row has been reached
            arr(i + j - 1, 1) = IIf(boolDark, C1, C2) 'load the aray with the appropriate string constant
        Next j
        boolDark = Not boolDark
 Next i

 'drop arr content, at once:
 dws.Range("B3").Resize(UBound(arr), 1).Value2 = arr
End Sub