สอบถามการแยกคอลัมน์

เริ่มโดย Earth, 20 มี.ค 18 , 14:36:21

หัวข้อก่อนหน้า - หัวข้อถัดไป

0 สมาชิก และ 1 ผู้มาเยือน กำลังดูหัวข้อนี้

Earth

จากรูปด้านล่างมีข้อมูลฟิลด์ Locationอยู่ค่ะ 
อยากทำQuery ให้แยกเป็น 2ฟิลด์ โดยมีเครื่องหมาย - เป็นตัวแยก
และเติม0ด้านหน้าแต่ละหลักในวรรค - ให้ครบ 9หลัก
ส่วนชนิดที่ไม่มี- ก็แยกตามรูปเลยค่ะ


รบกวนขอแนวทางด้วยค่ะ
  •  

pizza_p

#1
สร้าง Module ขึ้นมาแล้วเอาฟังก์ชั่นนี้ไปใส่
Public Function FormatLocation(stLocation As String, zone_or_id As Byte) As String
Dim splitText() As String, nPart As Integer, stResult As String

splitText = Split(stLocation, "-")
nPart = UBound(splitText)
stResult = ""
If zone_or_id = 1 Then
    stResult = splitText(0)
Else
    If nPart > 0 Then
        For i = 1 To nPart
            stResult = stResult & Format(splitText(i), "000")
        Next i
    Else
        stResult = "00000000"
    End If
End If
FormatLocation = stResult

End Function


เสร็จแล้วก็สามารถใช้ Query แบบนี้ได้
SELECT Location, FormatLocation([Location],1) AS Zone, FormatLocation([Location],2) AS ID FROM tblName;

  •  

Earth

ทำตามตัวอย่างขึ้นError แบบนี้ค่ะ

  •  

pizza_p

เพิ่ม i As Integer เข้าไปบรรทัดนี้ครับ

Dim splitText() As String, nPart As Integer, stResult As String, i As Integer
  •  
    โพสต์นี้ได้รับคำขอบคุณจาก: Earth

Earth

รบกวนอีกรอบนะคะ

คือถ้าต้องการเปลี่ยน เช่น
CC-4-1-1 เป็น  zone= CC,   ID= 00400101 (3หลัก 3หลัก 2หลัก) จากเดิมที่เป็น 004001001
ต้องเปลี่ยนจุดไหนบ้างคะ

ขอบคุณค่ะ
  •  

pizza_p

มันเป็นแบบนี้ทุกตัว หรือเฉพาะ CC
  •  

Earth

  •  

pizza_p

Public Function FormatLocation(stLocation As String, zone_or_id As Byte) As String
Dim splitText() As String, nPart As Integer, stResult As String, i As Integer

splitText = Split(stLocation, "-")
nPart = UBound(splitText)
stResult = ""
If zone_or_id = 1 Then
    stResult = splitText(0)
Else
    If nPart > 0 Then
        For i = 1 To nPart
            If i = nPart then
                stResult = stResult & Format(splitText(i), "00")
            Else
                stResult = stResult & Format(splitText(i), "000")
            End If
        Next i
    Else
        stResult = "00000000"
    End If
End If
FormatLocation = stResult

End Function
  •  
    โพสต์นี้ได้รับคำขอบคุณจาก: Earth