
มีโจทย์ว่าเรามีข้อมูลที่ได้จากระบบแบบหนึ่ง แต่เราจะนำข้อมูลมาใช้ให้ลงในข้อมูลที่แบบหนึ่ง และให้ข้อมูลมาต่อ ๆ กันไปเรื่อย ๆ หรือเรามีข้อมูล 2 ชุด แต่ต้องการเอามารวมเป็น ชุดเดียวกัน ถ้าวิธีแบบบ้าน ๆ ก็ต้องทำการ copy ข้อมูลแต่ละ Column มาลงให้ถูกต้อง ถ้าข้อมูลไม่มากอาจทำได้ง่าย แต่ถ้าข้อมูลเยอะ ๆ อาจเกิดการผิดพลาดได้ วันนี้จึงอยากแนะนำ Code ที่ใช้ในการ Load ข้อมูล ครับ
Code
Private Sub cmdLoad_Click()
' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook
Dim lRow As Long
' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Excel files (*.xls),*.xls,Excel files (*.xlsx),*.xlsx" ' นามสกุลที่สามารถใช้ได้ .xls, .xlsx
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)
If customerFilename = "False" Then
Exit Sub
End If
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
' copy ข้อมูลลง Workbook ตาม Field ที่ต้องการ
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1) ' Sheet Target
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1) ' Sheet Source
lRow = Cells(Rows.Count, 1).End(xlUp).Row 'ตรวจสอบ Row สุดท้าย
i = 6 ' Row แรกที่ต้องการ
j = lRow + 1 ' บวกเพิ่ม Row ถัดไป
Do While sourceSheet.Range("B" & i).Value <> "" ' ตรวจสอบว่าข้อมูลหมดหรือยัง
targetSheet.Range("A" & j).Value = sourceSheet.Range("B" & i).Value
targetSheet.Range("B" & j).Value = sourceSheet.Range("F" & i).Value
targetSheet.Range("N" & j).Value = sourceSheet.Range("D" & i).Value
targetSheet.Range("O" & j).Value = sourceSheet.Range("C" & i).Value
targetSheet.Range("V" & j).Value = sourceSheet.Range("G" & i).Value
i = i + 1
j = j + 1
Loop
' Close customer workbook
customerWorkbook.Close
End Sub
Example
Program Load Data >>>>Download
Good Luck
0 ความคิดเห็น:
แสดงความคิดเห็น