vba计数器,从每个循环中的不同单元格获取值

时间:2017-07-12 08:49:41

标签: vba

我自己解决了这个问题,感谢那些提供帮助的人

我有一个依赖于计数器的if语句,我从单元格“B3”获取计数器的值,并且代码工作正常。 但是每次我循环执行程序时,我都需要计数器从不同的单元格中获取它的值。 例如,循环1从“B3”读取值 循环2从“C3”读取值 下一页“D3”等表格 继续前进,直到它到达一个空单元格 我把dim c作为整数 并且对于c = 2到26,带我到第26列 但我不知道如何在每次循环开始时增加它。有人能帮忙吗?如果这有助于理解问题,我可以发布我正在使用的完整代码

Public Sub copyX()
Dim listofcells As Range
Dim currentname As String
Dim foundrow As Integer
Dim foundcolumn As Integer
Dim counter As Integer
Dim i As Integer
Dim c As Integer

For i = 2 To 26

    Sheets("Availability").Activate
    counter = Range("b3")
    Sheets("Availability").Range("a2").Select
    If Not Sheets("Availability").Cells(2, i) = "" Then
        Sheets("Availability").Range(Cells(2, i), Cells(2, i).End(xlDown)).Select
    Else
        GoTo skip:  'If the column has no data then skip to next column
    End If
    Set listofcells = Selection

    Sheets("allocation").Activate
    Range("a2").Select


    For Each singlecell In listofcells
            If counter > 0 Then
            If singlecell = "Available" Then
            foundcolumn = singlecell.Column 'record the column number where "Available" was found
            currentname = Sheets("availability").Range("A" & singlecell.Row) 'record the name of the person in the row where "Available" was found
            Set foundName = Sheets("allocation").Range("A:A").Find(What:=currentname, LookIn:=xlValues) 'find the persons name in "Allocation" sheet
            foundrow = foundName.Row
            Sheets("allocation").Cells(foundrow, foundcolumn) = "X" 'place yes in the same cell as it appeared in "Availability" sheet
            counter = counter - 1
            End If
        End If

    Next singlecell

skip:
Next i

End Sub

我已经提出了以下代码,它通过单元格获取它们的值,问题是我无法获得下一个循环在另一个循环中工作。 设置计数器=范围(“b3:Z3”)     对于每个细胞在计数器中     下一个单元格

1 个答案:

答案 0 :(得分:0)

尝试这个概念......

将您的代码修改为

Dim k as Integer

k=3;

counter =Range(Cells(3, k), Cells(3, k)).Value    // through this you will get dynamic counter value like B3,D3,E3.,,,,

if(counter !="")
{
//execute some code
}
k=k+1;