
ผมทำเป็นตัวอย่าง Code การปรับให้ Loop ในชีท Search ตั้งแต่ A2 เป็นต้นไป ซึ่งเป็นส่วนที่แจ้งมาว่าไม่สามารถเขียนให้ Loop ได้
ส่วนหากคำตอบไม่ได้ตามต้องการคุณต้องไปตรวจสอบดูว่า Code ที่เขียนมานั้นถูกต้องแล้วหรือไม่ อย่างไร แล้วค่อยนำถามกันต่อ
Code: Select all
Option Explicit
Sub Button2_Click()
Dim Find, item, parent2, child2, ra, ra2, rb, y, lot, slotP, i ' declare i
Dim elotP, r, re, re1, re2, ma1, ma2, parentR As Range 'declare parentR as range
item = Sheets("search").Range("A2").Value
lot = Sheets("search").Range("B2").Value
r = 2
re = 1
re1 = 2
re2 = 1
ma1 = 2
i = 0 ' assign value to i
Set parentR = Sheets("result").Range("A2") 'set object to parentR
Do While parentR.Offset(i, 0).Value <> ""
Do While Sheets("M_BOM").Cells(ma1, "A") <> ""
If Sheets("M_BOM").Cells(ma1, "A") = parentR Then
parent2 = Sheets("M_BOM").Cells(ma1, "A")
child2 = Sheets("M_BOM").Cells(ma1, "C")
slotP = Sheets("M_BOM").Cells(ma1, "G")
elotP = Sheets("M_BOM").Cells(ma1, "H")
If lot >= slotP And lot <= elotP Then
ma2 = 1
Find = 0
Do While Sheets("result").Cells(ma2, "A") <> ""
If Sheets("result").Cells(ma2, "A") = child2 Then
Find = 1
Exit Do
End If
ma2 = ma2 + 1
Loop
If Find = 1 Then
Sheets("result").Cells(re2, "F") = child2
re2 = re2 + 1
Else
Sheets("result").Cells(re, "G") = "(" & parent2 & ") "
Sheets("result").Cells(re, "H") = child2
Sheets("result").Cells(re, "I") = slotP
Sheets("result").Cells(re, "J") = elotP
re = re + 1
End If
End If
End If
ma1 = ma1 + 1
Loop
i = i + 1
Loop
End Sub