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

如何在VBA中使用Offset函数选择多个非连续单元格作为范围?

解决方法

直接上修改后的代码,能精准选中每间隔12行的姓名单元格,适配数据下移的情况:

Dim nameBank As Range
Dim lastRow As Long
Dim currentRow As Long

' 获取P列最后一个非空单元格的行号
lastRow = Cells(Rows.Count, "P").End(xlUp).Row

' 起始行按你的例子设为2,要是实际起始行不同,改这里就行
currentRow = 2

' 循环遍历所有符合间隔12行的单元格
Do While currentRow <= lastRow
    If nameBank Is Nothing Then
        ' 初始化第一个单元格
        Set nameBank = Cells(currentRow, "P")
    Else
        ' 把后续符合条件的单元格添加到范围里
        Set nameBank = Union(nameBank, Cells(currentRow, "P"))
    End If
    ' 每次跳12行
    currentRow = currentRow + 12
Loop

' 选中最终的姓名单元格范围
If Not nameBank Is Nothing Then nameBank.Select

代码说明

  • lastRow:动态获取P列最后一行数据的行号,不管数据怎么下移都能准确找到边界
  • currentRow:设置姓名出现的起始行(你的例子是P2,要是实际起始行是别的数,直接改这个值就行)
  • Do While循环:从起始行开始,每次加12,直到超过最后一行,把每个符合条件的单元格用Union合并成一个范围
  • 最后判断nameBank不为空时再选中,避免报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 13:42:07