You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA 遍历单元格按指定次数生成序列填充A列的实现方法

VBA实现代码
Sub GenerateSequenceInColumnA()
    Dim lastRow As Long
    Dim currentWriteRow As Long
    Dim i As Long
    Dim repeatCount As Long
    Dim content As String
    
    ' 设置A列写入起始行
    currentWriteRow = 1
    ' 获取C列最后一行有数据的行号,限定遍历范围
    lastRow = Cells(Rows.Count, "C").End(xlUp).Row
    
    For i = 1 To lastRow
        repeatCount = Val(Cells(i, "B").Value)
        content = Trim(Cells(i, "C").Value)
        
        ' 忽略无效行:B列值为0/空白、C列空白的行直接跳过
        If repeatCount > 0 And content <> "" Then
            ' 批量写入对应次数的内容到A列
            Range("A" & currentWriteRow & ":A" & currentWriteRow + repeatCount - 1) = content
            ' 偏移到下一个写入起始位置
            currentWriteRow = currentWriteRow + repeatCount
        End If
    Next i
End Sub

代码说明

  • 无需手动调整遍历范围,会自动识别C列最后一行有效数据作为遍历终点
  • 自动过滤空白单元格,符合忽略无效行的要求
  • 采用批量赋值方式而非逐行循环,数据量较大时运行效率更高
  • 按顺序写入A列,不会出现内容覆盖问题

内容的提问来源于stack exchange,提问作者jshvt17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 14:15:00