excel - 如何使用VBA设置动态单元格范围?

标签 excel vba

假设我编写了一个循环,但需要设置很多范围才能使其工作。如何设置一个范围来包含分布在工作表中的单元格。假设在每一行中,我想从 J 列、S 列、T 列......一直到 GB 列(每列之间有 5 列)选择单元格。我的伪脚本是这样的:

Sub CountPubs()


    Dim i, j As Long
    Dim Quant As Range

    i = 2
    j = 5
    While i <= 400

    Set Quant=Cells("I" & i),("I+j" & i),("I+2j" & i)... 

所以 Set 线很糟糕。每次满足条件时,循环本身都会增加 i ,但我希望分布在第 i 行的 36 个单元格(如 Quant 定义)也增加。我怎样才能完成设置定量线以实现此目的?

编辑:在我的测试中,我什至无法获得更简单的版本。如果我只是为了让这个进展到 T,我想脚本会是:

Sub CountPubs()
    Dim Count As Range
    Dim i As Long
    Dim Publications As Range
    i = 2
    Set Count = Range("C" & i)
    Set Publications = Range("I" & i), ("O" & i), ("T" & i)

但这给了我一个编译错误,参数数量错误或属性分配无效。我在这里错误地定义了最后一个范围吗?

最佳答案

您可以使用Union method创建一系列不相邻的单元格。

在您的场景中,您可以使用以下内容:

Sub unionCells()
    Dim i, j As Long
    Dim Quant As Range

    i = 2
    j = 5
    While i <= 400
        Set Quant = Union(Cells(9, i), Cells(9 + j, i), Cells(9 + 2 & j, i))
    Wend
End Sub

您还可以查看this answer关于使用联合。

关于excel - 如何使用VBA设置动态单元格范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31940691/

相关文章:

excel - 我怎样才能让我的超链接工作? (Excel,VBA)

python-3.x - python : Paste Excel cells with win32com to Powerpoint without losing cell formats

excel - VB Excel宏代码错误-msxml3.dll -2146697211系统无法找到指定的资源

VBA:回答 "save as - overwrite"提示(和其他)不使用默认选项

excel - 如果其他两个单元格匹配,则选择一个单元格的宏

excel - 在 Change 事件上更新范围的背景颜色索引

excel - 有没有办法在 excel vba 代码中获取列的迭代?

excel - VBA 用户窗体 : SpinButtons not working when TextBoxes are formatted using Class Module

vba - 无法使用 Excel 宏循环遍历 Excel 工作表?

Excel VBA 中的数组。在某些时候,它会放置 NA 而不是 value