Excel在单元格等于值时执行获取相邻单元格的时间

时间:2018-07-26 09:54:12

标签: excel vba excel-vba foreach do-while

我有两张纸。工作表1(客户跟踪程序-OC)的一列中,每一行都包含“是”或“否”。如果值为yes,则右边两个相邻的单元格中将有两个值。

我想为在工作表Sheet1的yes / no列中的每个单元格之间循环的每个宏创建一个do while /,其中值是yes,在空白工作表2中创建一个新行,其中有两个相邻的值从第1页开始。

Sheet1

   A    B    C
1  YES  4    6 
2  NO 
3  YES  91   42

工作表2中的期望结果(“合同”)

   A    B
1  4    6 
2  91   42

我有以下代码,但由于“溢出”而出错。

    Sub ForEach_Loop()

Dim TrackerLastRow As Integer
Dim TrackerCurrentRow As Integer
Dim ContractLastRow As Integer
Dim ContractCurrentRow As Integer

TrackerLastRow = Worksheets("Customer Tracker - OC").Range("T1").End(xlDown).Row
    TrackerCurrentRow = 1

    ContractLastRow = Worksheets("Contracts").Range("A1").End(xlDown).Row
    ContractCurrentRow = 1

    Do While TrackerCurrentRow <= TrackerLastRow

      If Worksheets("Customer Tracker - OC").Range("T" & TrackerCurrentRow).Value = "Yes" Then
            Worksheets("Contracts").Range("A" & ContractCurrentRow) = Worksheets("Customer Tracker - OC").Range("T" & TrackerCurrentRow).Offset(, 1).Value
            Worksheets("Contracts").Range("B" & ContractCurrentRow) = Worksheets("Customer Tracker - OC").Range("T" & TrackerCurrentRow).Offset(, 2).Value
            TrackerLastRow = TrackerLastRow + 1
            TrackerCurrentRow = TrackerCurrentRow + 1
            ContractLastRow = ContractLastRow + 1
            ContractCurrentRow = ContractCurrentRow + 1
        End If

        TrackerCurrentRow = TrackerCurrentRow + 1
        ContractCurrentRow = ContractCurrentRow + 1

        Loop


End Sub

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

似乎您过度增加了var,并过度扩展了整数类型var的功能限制。

{}

答案 1 :(得分:0)

我设法解决了这个问题,我确实更改为整数并删除了一些不必要的增量。认为我起初有点困惑。感谢您的帮助!

    Sub ForEach_Loop()

Dim TrackerLastRow As Long
Dim TrackerCurrentRow As Long
Dim ContractLastRow As Long
Dim ContractCurrentRow As Long

TrackerLastRow = 2486
    TrackerCurrentRow = 3


    ContractCurrentRow = 1

    Do While TrackerCurrentRow <= TrackerLastRow

      If Worksheets("Customer Tracker - OC").Range("T" & TrackerCurrentRow).Value = "Yes" Then

            Worksheets("Contracts").Range("A" & ContractCurrentRow) = Worksheets("Customer Tracker - OC").Range("T" & TrackerCurrentRow).Offset(, 1).Value
            Worksheets("Contracts").Range("B" & ContractCurrentRow) = Worksheets("Customer Tracker - OC").Range("T" & TrackerCurrentRow).Offset(, 2).Value

            TrackerCurrentRow = TrackerCurrentRow + 1
            ContractCurrentRow = ContractCurrentRow + 1

            Else

            TrackerCurrentRow = TrackerCurrentRow + 1

        End If



        Loop


End Sub