
กรณีไม่ต้องการหัวคอลัมน์และบรรทัดว่างมาด้วยต้องใส่เงื่อนไขเข้าไปเพิ่มครับ เช่น
Code: Select all
'Other code ' ลูปผ่านชีทที่ไม่มีคำว่า "CP" ในชื่อ และไม่ใช่ชีท "Paid_Yes", "Paid_No", "Main"
For Each ws In ThisWorkbook.Sheets
If Not InStr(1, ws.Name, "CP") > 0 And ws.Name <> "Paid_Yes" And ws.Name <> "Paid_No" And ws.Name <> "Main" Then
lastRowNonCP = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row
' ลูปผ่านข้อมูลในคอลัมน์ C ของชีท CP
For i = 10 To lastRowCP
If Not IsEmpty(wsCP.Cells(i, "A")) And IsNumeric(wsCP.Cells(i, "A")) Then
foundMatch = False
' ลูปผ่านข้อมูลในคอลัมน์ C ของชีท Non-CP
For j = 9 To lastRowNonCP
If wsCP.Cells(i, "C").Value = ws.Cells(j, "C").Value Then
foundMatch = True
Exit For
End If
Next j
' ถ้าไม่พบข้อมูลที่ตรงกัน ให้คัดลอกแถวนั้นไปวางในชีท Paid_No
If Not foundMatch Then
wsCP.Range(wsCP.Cells(i, "A"), wsCP.Cells(i, "AQ")).Copy
wsPaidNo.Cells(lastRowPaidNo + 1, "B").PasteSpecial Paste:=xlPasteValues
lastRowPaidNo = lastRowPaidNo + 1
End If
End If
Next i
End If
Next ws
'Other code
ดูเหมือนจะได้ค่าซ้ำ ๆ มาด้วย
สำหรับ Code ด้านล่างจะนำมาใช้เฉพาะค่าที่ไม่ซ้ำครับ
Code: Select all
Sub CopyRowsBasedOnCondition_()
Dim dCp As Object, strCp As String, rngCPs As Range, rngCp As Range
Dim dnCp As Object, strNcp As String, rngNCps As Range, rngNcp As Range
Dim sh As Worksheet, itm As Variant, i As Integer, strShN As String, rw As Integer
Set dCp = CreateObject("Scripting.Dictionary")
Set dnCp = CreateObject("Scripting.Dictionary")
For Each sh In Worksheets
If InStr(sh.Name, "CP") Then
Set rngCPs = sh.Range("c10", sh.Range("c" & sh.Rows.Count).End(xlUp))
For Each rngCp In rngCPs
strCp = CStr(rngCp.Value)
If IsNumeric(strCp) And Not dCp.Exists(strCp) Then
dCp.Add Key:=strCp, Item:=sh.Name & "|" & rngCp.Row
End If
Next rngCp
ElseIf InStr("Main|Paid_No|Paid_Yes|CP", sh.Name) = 0 Then
Set rngNCps = sh.Range("c9", sh.Range("c" & sh.Rows.Count).End(xlUp))
For Each rngNcp In rngNCps
strNcp = CStr(rngNcp.Value)
If IsNumeric(strNcp) And Not dnCp.Exists(strNcp) Then
dnCp.Add Key:=strNcp, Item:=sh.Name & "|" & rngNcp.Row
End If
Next rngNcp
End If
Next sh
For Each itm In dCp.keys
If Not dnCp.Exists(itm) Then
strShN = VBA.Split(dCp.Item(itm), "|")(0)
rw = VBA.Split(dCp.Item(itm), "|")(1)
With Worksheets("Paid_No")
.Range("a" & .Rows.Count).End(xlUp).Offset(1, 0).Resize(, 177).Value = _
Worksheets(strShN).Cells(rw, "a").Resize(, 177).Value
End With
End If
Next itm
End Sub