Video : Macro VBA Excel - Mencari data di Worksheet Database dan menampilkannya di User Form dan Penjelasannya
Tutorial Level 6
Membahas bagaimana caranya menggunakan Macro VBA Excel untuk mencari data berdasarkan keyword yang dituliskan pada sebuah textbox, yang hasilnya akan memunculkan daftar data yang sesuai keyword pada sebuah listbox.
Kemudian pengguna dapat memilih daftar data tersebut untuk menampilkan data lengkapnya pada beberapa textbox yang disiapkan di User Form.
Pada akhir video, dilengkapi dengan pembahasan sangat lengkap berikut penjelasan yang detil di setiap baris kode programnya.
Kode Program 1 pada Module:
Sub Cari()
Dim NamaCr As String
Dim NamaAr() As String, NikAr() As String
Dim i As Long, j As Long
Dim WB1 As Workbook
Dim WS1_1 As Worksheet
Dim WS1_2 As Worksheet
Set WB1 = ThisWorkbook
Set WS1_1 = WB1.Worksheets("Front")
Set WS1_2 = WB1.Worksheets("Database")
With UserForm1
If .TextBox1.Value <> "" Then
NamaCr = .TextBox1.Value
Else
MsgBox "Masukkan keyword pencarian!"
Exit Sub
End If
End With
With WS1_2.Range("B:B")
Set c = .Find(NamaCr, LookIn:=xlValues)
If Not c Is Nothing Then
j = 0
firstAddress = c.Address
Do
If c.Row <> 1 Then
ReDim Preserve NikAr(j) As String
ReDim Preserve NamaAr(j) As String
NikAr(j) = WS1_2.Cells(c.Row, 1).Value
NamaAr(j) = WS1_2.Cells(c.Row, 2).Value
j = j + 1
End If
Set c = .FindNext(c)
Loop While Not c Is Nothing And c.Address <> firstAddress
Else
MsgBox "Maaf, data tidak ditemukan.."
Exit Sub
End If
End With
With UserForm1
.ListBox1.Clear
For i = 0 To UBound(NikAr)
.ListBox1.AddItem
.ListBox1.List(i, 0) = NikAr(i)
.ListBox1.List(i, 1) = NamaAr(i)
Next i
End With
End Sub
Kode Program 2 pada Module:
Sub TampilkanData()
Dim NikCr As String, Nama As String, Nik As String, Almt As String, PndTrkr As String, JnsKlmn As String
Dim WB1 As Workbook
Dim WS1_1 As Worksheet
Dim WS1_2 As Worksheet
Set WB1 = ThisWorkbook
Set WS1_1 = WB1.Worksheets("Front")
Set WS1_2 = WB1.Worksheets("Database")
With UserForm1
If .ListBox1.ListIndex <> -1 Then
NikCr = .ListBox1.List(.ListBox1.ListIndex, 0)
Else
MsgBox "Data belum tersedia. Lakukan pencarian terlebih dahulu.."
Exit Sub
End If
End With
With WS1_2.Range("A:A")
Set c = .Find(NikCr, LookIn:=xlValues)
If Not c Is Nothing Then
Nik = WS1_2.Cells(c.Row, 1).Value
Nama = WS1_2.Cells(c.Row, 2).Value
Almt = WS1_2.Cells(c.Row, 3).Value
PndTrkr = WS1_2.Cells(c.Row, 4).Value
JnsKlmn = WS1_2.Cells(c.Row, 5).Value
Else
MsgBox "Maaf, data tidak ditemukan.."
Exit Sub
End If
End With
With UserForm1
.TextBox2.Value = Nik
.TextBox3.Value = Nama
.TextBox4.Value = Almt
.TextBox5.Value = PndTrkr
.TextBox6.Value = JnsKlmn
End With
End Sub
Kode Program 3 pada Module:
Sub MunculkanForm()
UserForm1.Show
End Sub
Kode Program pada UserForm:
Private Sub CommandButton1_Click()
Cari
End Sub
Private Sub ListBox1_Click()
TampilkanData
End Sub