在excel VBA中移动范围

时间:2016-08-09 16:43:05

标签: excel vba excel-vba

我需要能够判断某个范围的20个单元格是否有内容,如果是,则直接在下面的范围内移动到下一个20个单元格。示例(Sue-do):如果Range(A1-B10)有项目,则移至范围(A11-B20)。最多只能有20个范围(所以400个单元格)。我有填充这些单元格的代码,但是如果选择了多于1个项目来覆盖数据,它会覆盖。

2 个答案:

答案 0 :(得分:0)

我想你想要这样的东西:

dim Emptiness as boolean
dim MyRange as range, Cell1 as range
dim i as integer, j as integer

set myrange=range("A1:B10")

for i=0 to 19
    j=10*i
    set myrange=myrange.offset(j,0)
    Emptiness=true
    for each cell1 in myrange
        if isempty(cell1)=false then
            emptiness=false
            exit for
        else
            emptiness=true
        endif
    next cell1

    if emptiness=true then
        'your code that populates
    endif

next i

答案 1 :(得分:0)

你可以试试这个

Option Explicit

Sub main()
    Dim i As Long

    With Worksheets("mySheet").Range("A1:B20") <--| change "MySheet" with your actual sheet name and "A1:B20" with your actual "initial" range
        For i = 0 To 19
            If WorksheetFunction.CountA(.Offset(i * 20)) = 0 Then
                ' code to populate
                ' remember that ".Offset(i * 20)" will return the found 20-rows-2-columns range with no data
                Exit For
            End If
        Next i
    End With
End Sub