เขียนสูตร VBA เพื่อรวม Sheet ให้มารวมกันเหมือนตัวอย่าง
Posted: Wed Jun 05, 2024 1:26 pm
เขียนสูตร VBA เพื่อรวม Sheet ให้มารวมกันเป็น ชีสเดียวแบบนี้
ผมลองดูแล้วมันมาไม่ครบครับ
ผมลองดูแล้วมันมาไม่ครบครับ
Code: Select all
Sub MergeSheets()
Dim mainSheet As Worksheet
Dim ws As Worksheet
Dim lastRow As Long
Dim targetRow As Long
Dim i As Long
On Error Resume Next
Set mainSheet = ThisWorkbook.Worksheets("MainSheet")
On Error GoTo 0
If mainSheet Is Nothing Then
Set mainSheet = ThisWorkbook.Worksheets.Add
mainSheet.Name = "MainSheet"
Else
' mainSheet.Cells.Clear
End If
mainSheet.Range("A1:R1").Value = Array("P/O No.", "Date", "CAPRE NO :", "Vendor Name", "Vendor Address", "Vendor Tell", "Credit Term:", "Refer P/R No :", "Dept.Order :", "Item", "Description", "Request Date", "Unit", "Qty", "Unit Price(Baht)", "Amount(Baht)", "Notes:1", "Notes:2", "Notes:3")
targetRow = 3
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> mainSheet.Name Then
lastRow = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row
For i = 18 To lastRow
If ws.Cells(i, "D").Value <> "" Then
mainSheet.Cells(targetRow, "A").Resize(1, 15).Value = ws.Range("L9:M9,M4,D10:E12,L13:L14").Value
mainSheet.Cells(targetRow, "I").Value = ws.Cells(i, "D").Value
mainSheet.Cells(targetRow, "J").Value = ws.Cells(i, "E").Value
mainSheet.Cells(targetRow, "K").Value = ws.Cells(i, "I").Value
mainSheet.Cells(targetRow, "L").Value = ws.Cells(i, "J").Value
mainSheet.Cells(targetRow, "M").Value = ws.Cells(i, "K").Value
mainSheet.Cells(targetRow, "N").Value = ws.Cells(i, "L").Value
mainSheet.Cells(targetRow, "O").Value = ws.Cells(i, "M").Value
mainSheet.Cells(targetRow, "P").Value = ws.Cells(i, "E").Offset(54, 0).Value
mainSheet.Cells(targetRow, "Q").Value = ws.Cells(i, "E").Offset(55, 0).Value
mainSheet.Cells(targetRow, "R").Value = ws.Cells(i, "E").Offset(56, 0).Value
targetRow = targetRow + 1
End If
Next i
End If
Next ws
End Sub