EXCEL TOOLS
Excel Add-ins ที่พัฒนาโดยคุณสันติพงศ์ ณสุย (MVP Excel 2010-2020) ด้วยภาษา C# เพื่อแก้ไขปัญหาไฟล์ใหญ่ คำนวณนาน ทำงานช้า จัดการข้อมูลต่าง ๆ ที่ทำงานประจำวันได้อย่างสะดวกรวดเร็ว สนใจคลิกไปดูได้ที่นี่ครับ => Excel Tools
Excel Add-ins ที่พัฒนาโดยคุณสันติพงศ์ ณสุย (MVP Excel 2010-2020) ด้วยภาษา C# เพื่อแก้ไขปัญหาไฟล์ใหญ่ คำนวณนาน ทำงานช้า จัดการข้อมูลต่าง ๆ ที่ทำงานประจำวันได้อย่างสะดวกรวดเร็ว สนใจคลิกไปดูได้ที่นี่ครับ => Excel Tools
[code]
และปิดด้วย [/code]
ตัวอย่างเช่น [code]dim r as range[/code]
เพื่อให้แตกต่างจากข้อความทั่วไป สะดวกในการอ่านและทดสอบ (คลิกเพื่อดูตัวอย่าง)Code: Select all
Private Sub CommandButton1_Click()
Dim RecordRow As Long
Dim RecordRange As Range
On Error Resume Next
RecordRow = Application.Match(CLng(TextBox1.Value), Range("Table1[id]"), 0)
Set RecordRange = Range("Table1").Cells(1, 1).Offset(RecordRow - 1, 0)
If Err.Number <> 0 Then
ErrorLabel.Visible = True
On Error GoTo 0
Exit Sub
End If
On Error GoTo 0
ErrorLabel.Visible = False
TextBox2.Value = RecordRange(1, 1).Offset(0, 1).Value
End Sub
Code: Select all
Private Sub CommandButton1_Click()
Dim RecordRow As Long, mText As Long, mNum As Long
Dim RecordRange As Range
ErrorLabel.Visible = False
On Error Resume Next
mText = Application.Match(TextBox1.Value, Range("Table1[id]"), 0)
mNum = Application.Match(CLng(TextBox1.Value), Range("Table1[id]"), 0)
RecordRow = Application.Max(mText, mNum)
TextBox2.Text = ActiveSheet.Cells(RecordRow, "b").Value
If RecordRow = 0 Then
ErrorLabel.Visible = True
End If
' Set RecordRange = Range("Table1").Cells(1, 1).Offset(RecordRow - 1, 0)
' If Err.Number <> 0 Then
'
' ErrorLabel.Visible = True
' On Error GoTo 0
' Exit Sub
'
' End If
'
On Error GoTo 0
'ErrorLabel.Visible = False
' TextBox2.Value = RecordRange(1, 1).Offset(0, 1).Value
End Sub
ปรับแก้ code ตามที่อาจารย์แนะนำแล้วครับ แต่ข้อมูลที่แสดงผลออกมาไม่ตรง ที่ textbox2 จะแสดงผลขึ้นแถว 1 แถว ไม่ตรงกับ id ที่ค้นหาครับsnasui wrote: Wed Oct 11, 2023 5:50 amคอลัมน์ ID มีทั้ง Data Type ที่เป็น Number และ Text การค้นหาจะต้องค้นหาทั้งสองรูปแบบ ปกติควรกำหนด Data Type ของคอลัมน์ใด ๆ ให้เป็นรูปแบบเดียวเท่านั้น การทำงานกับข้อมูลจะต้องคำนึงถึงสิ่งนี้เป็นสำคัญครับ
ตัวอย่างการปรับ Code ให้หาได้ทั้ง Text และ Number (ซึ่งไม่แนะนำ)
Code: Select all
Private Sub CommandButton1_Click() Dim RecordRow As Long, mText As Long, mNum As Long Dim RecordRange As Range ErrorLabel.Visible = False On Error Resume Next mText = Application.Match(TextBox1.Value, Range("Table1[id]"), 0) mNum = Application.Match(CLng(TextBox1.Value), Range("Table1[id]"), 0) RecordRow = Application.Max(mText, mNum) TextBox2.Text = ActiveSheet.Cells(RecordRow, "b").Value If RecordRow = 0 Then ErrorLabel.Visible = True End If ' Set RecordRange = Range("Table1").Cells(1, 1).Offset(RecordRow - 1, 0) ' If Err.Number <> 0 Then ' ' ErrorLabel.Visible = True ' On Error GoTo 0 ' Exit Sub ' ' End If ' On Error GoTo 0 'ErrorLabel.Visible = False ' TextBox2.Value = RecordRange(1, 1).Offset(0, 1).Value End Sub