Visual BaSic belajaR Source Code


Check For a File

Public Function FileExist(asPath as string) as Boolean
If UCase(Dir(asPath))=Ucase(trimPath(asPath)) then
FileExist=true
Else

FileExist=False
End If
End Function

Public Function TrimPath(ByVal asPath as string) as string

if Len(asPath)=0 then Exit Function
Dim x as integer
Do

x=Instr(asPath,”\”)
if x=0 then Exit Do
asPath=Right(asPath,Len(asPath)-x)
Loop
TrimPath=asPath
End Function

Private sub command1_Click()
if fileExist(Text1.text) then

Label1=”YES”
else
Label1=”NO”
End if
End Sub

Private sub form_Load()
End sub

Low and Upper Case

‘add 2 command buttons and 1 text

Private Sub Command1_Click()
Text1.Text = CapFirst$(Text1.Text)
End Sub

Private Sub Command2_Click()

Text1.Text = LCase$(Text1.Text)
End Sub

‘add 1 module
Declare Function CapFirst$ Lib “CAPFIRST.DLL” Alias “CAPFIRST” (ByVal St$)

Show Your IP Address

Add Microsoft Winsock Control 6.0 component

Insert 1 Textbox
Insert 2 Command Buttons Rename Caption as Display and Clear

Private Sub Command1_Click()
If Text1.Text = “” Then
Command1.Enabled = False
Text1.Text = Winsock1.LocalIP
Else

Command1.Enabled = True
End If
End Sub

Private Sub Command2_Click()
Text1.Text = “”
If Text1.Text = “” Then
Command1.Enabled = True
Else

Command1.Enabled = False
End If
End Sub

Private Sub Form_Load()
Text1.Text = “”
If Text1.Text = “” Then
Command1.Enabled = False
Else
Command1.Enabled = True
End If
Text1.Text = Winsock1.LocalIP
End Sub

Permutasi

Option Explicit

Dim id As Integer
Dim N As Integer
Dim perm() As Integer

Function Engine(i As Integer)

Dim t As Integer
Dim j As Integer

id = id + 1
perm(i) = id
If (id = N) Then stampaj
For j = 1 To N
If (perm(j) = 0) Then
Engine (j)
End If
DoEvents
Next j
id = id – 1
perm(i) = 0
End Function

Private Sub cmdClear_Click()
List1.Clear
End Sub

Private Sub cmdGen_Click()
If Val(txtLength.Text) > Len(txtChar.Text) Then
MsgBox “Jumlah Permutasi Salah”

Exit Sub
End If

If Len(txtChar.Text) = 0 Or (Val(txtLength.Text) = 0) Then Exit Sub

Dim i As Integer
N = Val(txtLength.Text)
ReDim perm(N)
For i = 1 To N
perm(i) = 0
Next i
If ChSave.Value = 1 Then
MsgBox “Disimpan pada hasil.txt”
Open App.Path + “\hasil.txt” For Output As #1
End If
Engine 0
If ChSave.Value = 1 Then Close #1

End Sub

Sub Form_Load()
On Error Resume Next
id = -1

End Sub

Sub stampaj()
Dim i As Integer
Dim result As String
result = “”
For i = 1 To N
result = result & CStr(Mid$(txtChar.Text, perm(i), 1))
Next i
List1.AddItem result
If ChSave.Value = 1 Then Print #1, result
End Sub

Enkripsi Searah

Public Function Hash(ByVal text As String) As String
a = 1
For i = 1 To Len(text)
a = Sqr(a * i * Asc(Mid(text, i, 1))) ‘Numeric Hash
Next i
Rnd (-1)
Randomize a ‘seed PRNG

For i = 1 To 16
Hash = Hash & Chr(Int(Rnd * 256))
Next i
End Function

Private Sub Form_Load()
MsgBox Hash(“EmZ-2509″)    ‘Yang dihasilkan: ‰°’r¿¾ ©Ì¿ÂX*¤W
End
End Sub

Enkripsi

Function EncDec(inData As Variant, Optional inPW As Variant = “”) As Variant
On Error Resume Next
Dim arrSBox(0 To 255) As Integer
Dim arrPW(0 To 255) As Integer
Dim Bi As Integer, Bj As Integer
Dim mKey As Integer
Dim i As Integer, j As Integer
Dim x As Integer, y As Integer
Dim mCode As Byte, mCodeSeries As Variant

EncDec = “”
If Trim(inData) = “” Then
Exit Function
End If

If inPW <> “” Then
j = 1
For i = 0 To 255
arrPW(i) = Asc(Mid$(inPW, j, 1))
j = j + 1
If j > Len(inPW) Then
j = 1
End If
Next i
Else

For i = 0 To 255
arrPW(i) = 0
Next i
End If

For i = 0 To 255
arrSBox(i) = i
Next i

j = 0
For i = 0 To 255
j = (arrSBox(i) + arrPW(i)) Mod 256
x = arrSBox(i)
arrSBox(i) = arrSBox(j)
arrSBox(j) = x
Next i

mCodeSeries = “”
Bi = 0: Bj = 0
For i = 1 To Len(inData)
Bi = (Bi + 1) Mod 256
Bj = (Bj + arrSBox(Bi)) Mod 256
‘ Tukar
x = arrSBox(Bi)

arrSBox(Bi) = arrSBox(Bj)
arrSBox(Bj) = x

‘siapkan kunci untuk XOR
mKey = arrSBox((arrSBox(Bi) + arrSBox(Bj)) Mod 256)

‘gunakan operasi XOR
mCode = Asc(Mid$(inData, i, 1)) Xor mKey
mCodeSeries = mCodeSeries & Chr(mCode)
Next i
EncDec = mCodeSeries
End Function

Private Sub Form_Load()
Dim Encrypt As String, Decrypt As String

Encrypt = EncDec(“admin”, “win”)
Decrypt = EncDec(“™D`­>”, “win”)
MsgBox “Hasil enkripsi : ” & Encrypt & _
vbCrLf & “Hasil dekripsi : ” & Decrypt
End
End Sub

Menu Pop Up

Option Explicit

Private Declare Function SendMessage Lib “user32″ Alias _
“SendMessageA” (ByVal hwnd As Long, ByVal wMsg As Long, _
ByVal wParam As Long, lParam As Any) As Long

Private Const LB_GETITEMRECT = &H198
Private Const LB_ERR = (-1)

Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type

Public Function GetRClickedItem(MyList As Control, _
X As Single, Y As Single) As Long

‘PURPOSE: Determine which item was right clicked in a list
‘box, from the list_box’s mouse down event.  YOU MUST CALL THIS
‘FROM THE MOUSEDOWN EVENT, PASSING THE X AND Y VALUES FROM THAT
‘EVENT TO THIS FUNCTION

‘MYLIST: ListBox Control
‘X, Y: X and Y position from MyList_MouseDown

‘RETURNS:  ListIndex of selected item, or -1 if
‘a) There is no selected item, or b) an error occurs.

Dim clickX As Long, clickY As Long
Dim lRet As Long
Dim CurRect As RECT
Dim l As Long

‘Control must be a listbox
If Not TypeOf MyList Is ListBox Then
GetRClickedItem = LB_ERR
Exit Function
End If

‘get x and y in pixels
clickX = X Screen.TwipsPerPixelX
clickY = Y Screen.TwipsPerPixelY

‘Check all items in the list to see if it was clicked on
For l = 0 To MyList.ListCount – 1

‘get current selection as rectangle
lRet = SendMessage(MyList.hwnd, LB_GETITEMRECT, l, CurRect)

‘If the position of the click is in the this list item
‘then that’s  our Item

If (clickX >= CurRect.Left) And (clickX <= CurRect.Right) _
And (clickY >= CurRect.Top) And _
(clickY <= CurRect.Bottom) Then

GetRClickedItem = l
Exit Function
End If
Next l
End Function

Private Sub Form_Load()
List1.AddItem “Merah”
List1.AddItem “Kuning”
List1.AddItem “Hijau”
mnuPopUp.Visible = False
End Sub

Private Sub List1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim lItem As Long

If Button = vbRightButton Then
lItem = GetRClickedItem(List1, X, Y)

If lItem <> -1 Then
List1.ListIndex = lItem
PopupMenu mnuPopUp
End If
End If

End Sub

Load Picture

Private Sub Command1_Click()
With Me.CommonDialog1
.DialogTitle = “Ambil Gambar”
.Filter = “JPEG|*.jpg”
.ShowOpen

If .FileName <> “” Then
Set Me.Picture1.Picture = Nothing
Me.Picture1.Picture = LoadPicture(.FileName)
End If
End With
End Sub

‘Private Sub Form_Load()
‘Me.Picture1.Picture = LoadPicture(“D:\gbr_motor\bikes_honda_01.jpg”)
‘End Sub

Sleep With Visual Basic

Option Explicit

Private Declare Sub Sleep Lib “kernel32″ (ByVal dwMilliseconds As Long)

Private Sub Form_Click()
Me.Caption = “Sleeping”
Call Sleep(20000)
Me.Caption = “Awake”
End Sub

Private Sub Label1_Click()
Me.Caption = “Sleeping”
Call Sleep(20000)
Me.Caption = “Awake”
End Sub

Form

Option Explicit

Private Declare Function GetWindowText Lib “user32″ Alias “GetWindowTextA” (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long

Private Sub cmdActivate_Click()
Dim nRet As Long
Dim Title As String

nRet = AppActivatePartial(Trim(txtTitle.Text), _
Val(frmMethod.Tag), CBool(chkCase.Value))
If nRet Then
lblResults.Caption = “Found: &&H” & Hex$(nRet)
Title = Space$(256)
nRet = GetWindowText(nRet, Title, Len(Title))
If nRet Then
lblResults.Caption = lblResults.Caption & _
“, “”” & Left$(Title, nRet) & “”””
End If
Else
lblResults.Caption = “Search Failed”
End If
End Sub

Private Sub Form_Load()

txtTitle.Text = “”
lblResults.Caption = “”
optMethod(0).Value = True
End Sub

Private Sub optMethod_Click(Index As Integer)

frmMethod.Tag = Index
End Sub

Module

Option Explicit

Private Declare Function EnumWindows Lib “user32″ (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
Private Declare Function GetClassName Lib “user32″ Alias “GetClassNameA” (ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function GetWindowText Lib “user32″ Alias “GetWindowTextA” (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function IsIconic Lib “user32″ (ByVal hWnd As Long) As Long
Private Declare Function IsWindowVisible Lib “user32″ (ByVal hWnd As Long) As Long
Private Declare Function ShowWindow Lib “user32″ (ByVal hWnd As Long, ByVal nCmdShow As Long) As Long
Private Declare Function SetForegroundWindow Lib “user32″ (ByVal hWnd As Long) As Long

Private Const SW_RESTORE = 9

Private m_hWnd As Long
Private m_Method As FindWindowPartialTypes
Private m_CaseSens As Boolean
Private m_Visible As Boolean
Private m_AppTitle As String

Public Enum FindWindowPartialTypes
FwpStartsWith = 0
FwpContains = 1
FwpMatches = 2
End Enum

Public Function AppActivatePartial(AppTitle As String, Optional Method As FindWindowPartialTypes = FwpStartsWith, Optional CaseSensitive As Boolean = False) As Long
Dim hWndApp As Long

hWndApp = FindWindowPartial(AppTitle, Method, CaseSensitive, True)
If hWndApp Then

If IsIconic(hWndApp) Then
Call ShowWindow(hWndApp, SW_RESTORE)
End If
Call SetForegroundWindow(hWndApp)
AppActivatePartial = hWndApp
End If
End Function

Public Function FindWindowPartial(AppTitle As String, _
Optional Method As FindWindowPartialTypes = FwpStartsWith, _
Optional CaseSensitive As Boolean = False, _
Optional MustBeVisible As Boolean = False) As Long

m_hWnd = 0
m_Method = Method
m_CaseSens = CaseSensitive
m_AppTitle = AppTitle

If m_CaseSens = False Then
m_AppTitle = UCase$(m_AppTitle)
End If

Call EnumWindows(AddressOf EnumWindowsProc, MustBeVisible)
FindWindowPartial = m_hWnd
End Function

Private Function EnumWindowsProc(ByVal hWnd As Long, ByVal lParam As Long) As Long
Static WindowText As String
Static nRet As Long

If lParam Then
If IsWindowVisible(hWnd) = False Then
EnumWindowsProc = True
Exit Function
End If
End If

WindowText = Space$(256)
nRet = GetWindowText(hWnd, WindowText, Len(WindowText))
If nRet Then

WindowText = Left$(WindowText, nRet)
If m_CaseSens = False Then
WindowText = UCase$(WindowText)
End If

Select Case m_Method

Case FwpStartsWith
If InStr(WindowText, m_AppTitle) = 1 Then
m_hWnd = hWnd
End If
Case FwpContains
If InStr(WindowText, m_AppTitle) <> 0 Then
m_hWnd = hWnd
End If
Case FwpMatches
If WindowText = m_AppTitle Then
m_hWnd = hWnd
End If
End Select
End If

EnumWindowsProc = (m_hWnd = 0)
End Function

.
Iklan
By Sanggar Rohman Posted in VB

Belajar VB


Pertama yang perlu disapkan adalah :

  • Nama Database : DBPembelajaran.mdb format Microsoft Office Access 2000
  • Nama Tabel : SiswaLogin
  • Nama Field dalam Tabel SiswaLogin : Nama Field Nama_Siswa TypeField Text dan field kedua Nama Field NIS TypeField Text
  • Klik Menu Project Pilih References.. : Microsoft ActiveX Data Object 2.0 Library atau versi yang lebih tinggi.

Dibawah ini serpihan kode yang mungkin bermanfaat, silahkan…
1. a. Koneksi Dengan Database Yang Tidak Berpassword

Option Explicit
Dim db As ADODB.Connection
Dim adoPrimaryRSLoginSiswa As ADODB.Recordset

Private Sub Form_Load()
On Error GoTo err
        Set db = New ADODB.Connection
        db.CursorLocation = adUseClient
        db.Open "PROVIDER=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=" & App.Path & "\DBPembelajaran.mdb;"
err:
        If db.State = 1 Then
            MsgBox "Terkoneksi dengan database"
        ElseIf db.State = 0 Then
            MsgBox "Tidak Terkoneksi dengan database.", vbInformation, "Error"
        End If
End Sub

1. b. Koneksi Dengan Database Berpassword

Private Sub Form_Load()
On Error GoTo ERR
        Dim DBBerPassword
        Set DBBerPassword = New ADODB.Connection
        DBBerPassword.CursorLocation = adUseClient
        DBBerPassword.Open "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\DBPembelajaran - Copy.mdb" & ";Persist Security Info=False;Mode=12;Jet OLEDB:Database Password=TulisPasswordnya"
ERR:
        If DBBerPassword.State = 1 Then
            MsgBox "Terkoneksi dengan database"
        ElseIf DBBerPassword.State = 0 Then
            MsgBox "Tidak Terkoneksi dengan database.", vbInformation, "Error"
        End If
End Sub

2. Buka Record

Private Sub Command1_Click()
On Error GoTo err
        Set adoPrimaryRSLoginSiswa = New ADODB.Recordset
        adoPrimaryRSLoginSiswa.Open "TblSiswaLogin", db, adOpenStatic, adLockOptimistic
err:
        If adoPrimaryRSLoginSiswa.State = 1 Then
            MsgBox "Terkoneksi dengan Tabel"
        ElseIf adoPrimaryRSLoginSiswa.State = 0 Then
            MsgBox "Tabel tidak ditemukan, cek kembali tabel yang ada dalam database.", vbInformation, "Error"
        End If
End Sub

3. Cek Isi Field

Private Sub Command2_Click()
    adoPrimaryRSLoginSiswa.MoveFirst
    MsgBox "NAMA FIELD : " & adoPrimaryRSLoginSiswa.Fields(0).Name & _
    vbCrLf & "ISI FIELD RECORD PERTAMA : " & adoPrimaryRSLoginSiswa.Fields(0).Value, vbInformation
End Sub

4. Menghubungkan Isi Field Ke Control

Private Sub Command3_Click()
    Set Me.Text1.DataSource = adoPrimaryRSLoginSiswa
    Set Me.Text2.DataSource = adoPrimaryRSLoginSiswa

    Me.Text1.DataField = "NAMA_SISWA"
    Me.Text2.DataField = "NIS"

End Sub

5. Mengecek Field Kosong (IsNull)

Private Sub Command4_Click()
    'DI PROPERTY Text3 MultiLine pilih True
    'DI PROPERTY Text3 ScrollBars pilih 3
    Text3.Text = "MENGECEK FIELD NIS KOSONG"
    adoPrimaryRSLoginSiswa.MoveFirst
    While Not adoPrimaryRSLoginSiswa.EOF
    If IsNull(adoPrimaryRSLoginSiswa.Fields("NIS")) = True Then
        Text3.Text = Text3.Text & vbCrLf & "NO : " & adoPrimaryRSLoginSiswa.AbsolutePosition & ". " & adoPrimaryRSLoginSiswa.Fields("NAMA_SISWA").Value & " KOSONG"
    ElseIf IsNull(adoPrimaryRSLoginSiswa.Fields("NIS")) = False Then
        Text3.Text = Text3.Text & vbCrLf & "NO : " & adoPrimaryRSLoginSiswa.AbsolutePosition & " TIDAK KOSONG "
    End If
        adoPrimaryRSLoginSiswa.MoveNext
    Wend
End Sub

6. Navigasi

Private Sub Command5_Click()
    If adoPrimaryRSLoginSiswa.AbsolutePosition = 1 Or adoPrimaryRSLoginSiswa.RecordCount = 0 Then
        Beep
    Else
        adoPrimaryRSLoginSiswa.MoveFirst 'Ke record Pertama
    End If
    Me.Label2.Caption = "NO. " & adoPrimaryRSLoginSiswa.AbsolutePosition
End Sub

Private Sub Command6_Click()
    If adoPrimaryRSLoginSiswa.AbsolutePosition = 1 Or adoPrimaryRSLoginSiswa.RecordCount = 0 Then
        Beep
    Else
        adoPrimaryRSLoginSiswa.MovePrevious "Ke record Sebelumnya    End If
    Me.Label2.Caption = "NO. " & adoPrimaryRSLoginSiswa.AbsolutePosition
End Sub

Private Sub Command7_Click()
    If adoPrimaryRSLoginSiswa.AbsolutePosition = adoPrimaryRSLoginSiswa.RecordCount Or adoPrimaryRSLoginSiswa.RecordCount = 0 Then
        Beep
    Else
        adoPrimaryRSLoginSiswa.MoveNext 'Ke record Selanjutnya    End If
    Me.Label2.Caption = "NO. " & adoPrimaryRSLoginSiswa.AbsolutePosition
End Sub

Private Sub Command8_Click()
    If adoPrimaryRSLoginSiswa.AbsolutePosition = adoPrimaryRSLoginSiswa.RecordCount Or adoPrimaryRSLoginSiswa.RecordCount = 0 Then
        Beep
    Else
        adoPrimaryRSLoginSiswa.MoveLast 'Ke record Terakhir    End If
    Me.Label2.Caption = "NO. " & adoPrimaryRSLoginSiswa.AbsolutePosition
End Sub

6. Mendapatkan Tabel Dalam database

Private Sub Command9_Click()
Dim NamaTabel As ADODB.Recordset
Set NamaTabel = db.OpenSchema(adSchemaTables)
    While Not NamaTabel.EOF
        If NamaTabel!TABLE_TYPE = "TABLE" Then Text4.Text = Text4.Text & vbCrLf & NamaTabel!TABLE_NAME
        NamaTabel.MoveNext
    Wend
End Sub

7. Mendapatkan Field Dalam Tabel

Private Sub Command10_Click()
Dim Column As ADODB.Field
If adoPrimaryRSLoginSiswa.State = adStateOpen Then
    For Each Column In adoPrimaryRSLoginSiswa.Fields
        Text5.Text = Text5.Text & vbCrLf & Column.Name
    Next
End If
End Sub

8. Membuat Tabel – Create Table

Private Sub Command11_Click()
    Dim Cmd As New ADODB.Command
    Cmd.ActiveConnection = db
    Cmd.CommandText = "create table TabelBaru (NAMA_SISWA varchar(20), KELAS varchar(5), TENTANG_SISWA LongChar, Foto LongBinary)"
    Cmd.Execute
End Sub

9. Menambahkan Field Di Tabel Yang Sudah Ada – Add Field In Exists Table

Private Sub Command12_Click()
'Tambahkan references Microsoft ADO Ext. 2.1 for DDL and Security atau versi lebih tinggi
    Dim Xconx As ADODB.Connection
    Dim Xcmd As ADODB.Command
    Dim Xrs As ADODB.Recordset
    Dim m_MDBdatabase As String
    Dim m_MDBtable As String

'Tambahkan columns di tabel yang sudah ada
    Dim ADOXcat As ADOX.Catalog
    Dim MStbl As ADOX.table
    Dim MScol As ADOX.Column

    m_MDBdatabase = App.Path & "\DBPembelajaran.mdb"
    m_MDBtable = "TblSiswaLogin"

'Membuat koneksi
    Set Xconx = New ADODB.Connection
    Set Xcmd = New ADODB.Command
    Set Xrs = New ADODB.Recordset
    Set Xconx = CreateObject("ADODB.Connection")
    Xconx.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Persist Security Info=False;" & _
    "Data Source=" & m_MDBdatabase
    Set Xrs = CreateObject("ADODB.Recordset")
    Xrs.CursorLocation = adUseServer

'Mengirimkan MDB dan table ke catalog
    Set ADOXcat = New ADOX.Catalog
    ADOXcat.ActiveConnection = _
    "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=" & m_MDBdatabase
    Set MStbl = ADOXcat.Tables(m_MDBtable)

'Menambahkan columns/Field ke tabel yang ada
    MStbl.Columns.Append "NILAI", adDouble
    MStbl.Columns.Append "KETERANGAN", adVarWChar, 255
    MStbl.Columns.Append "TANGGAL_LAHIR", adDate

'Bersihkan
    ADOXcat.ActiveConnection.Close
    Set ADOXcat = Nothing
    Set MStbl = Nothing
    Set MScol = Nothing
    Set Xconx = Nothing
    Set Xcmd = Nothing
    Set Xrs = Nothing
End Sub

10. Hapus Semua Record Dalam Tabel

Private Sub Command13_Click()
    db.Execute "DELETE FROM TBLsiswalogin"
End Sub

11. Hapus Tabel

Private Sub Command14_Click()
'Tambahkan references Microsoft DAO 3.6 Object Library atau versi lebih tinggi
    Dim ConMateri As Database, AdoDao%
    Set ConMateri = OpenDatabase(App.Path & "\DBPembelajaran.MDB", False, False, "MS Access;Pwd=dbpwd")
    Dim TbDef As TableDefs
    Set TbDef = ConMateri.TableDefs
    ConMateri.TableDefs.Delete "NamaTabelYangAkanDiHapus"
End Sub
By Sanggar Rohman Posted in VB Dengan kaitkata