[VB6] Read Excel Files


Deskripsi
     To read data cell in Excel files.

Howto
   Dim oexcel As Object
   Dim obook As Object
   Dim osheet As Object
   Dim var As Variant

   Set oexcel = CreateObject("Excel.Application")
   Set obook = oexcel.workbooks.Open("D:\Developer\sample.xlsx")
   Set osheet = obook.worksheets(1)

   ' you can read with two method, just uncomment below
   ' var = osheet.Range("A1").Value
   'or
   'var = osheet.Cells(1, 1).Value 'Row , Column

   MsgBox var
   Set osheet = Nothing
   obook.Close
   oexcel.Quit

[VB6] Using Regular Expression in String


Deskripsi
     Using Regular Expression or Regex in VB is very simply , we just need project refference , string we want to get and then the pattern.

Howto
1.  Project > Components > Microsoft VBscript Regular Expressions 5.5
2.  Write code below
'Create variable
Dim html as string
Dim myRegExp As regexp ' for create object
Dim myMatches As MatchCollection ' collection matches string (raw)
Dim myMatch As Match ' matches string

Set myRegExp = New regexp
myRegExp.IgnoreCase = True 'case insensitive
myRegExp.Global = True
' create your pattern , for example i use pattern that grab some string in web page source using regex.
myRegExp.Pattern = "<td style=" & """height:50px;""" & ">(.*)</td>"

'execute raw string, for example in html page source i have raw string
Set myMatches = myRegExp.Execute(html)

'to get string that matches with pattern
MsgBox myMatches.Count

For Each myMatch In myMatches   'get the match string.
      msgbox myMatch.Value
Next

*tips : if you still confuse create the pattern for regex , you can learn from www.regexpal.com to test your regex, just input raw string and create the pattern.
the pattern which match raw string will be highlight with a color, good website i think...
it save my time create a regex :)



[VB6] Write to file text


Deskripsi
    Write to file with format text using VB 6

Howto

    Dim sFileText As String
    Dim iFileNo As Integer
 
    iFileNo = FreeFile
    'open the file for writing
    Open "D:\myfile.txt" For Output As #iFileNo
    'please note, if this file already exists it will be overwritten!

    'write some example text to the file
    Print #iFileNo, "My String 1 Here"
    Print #iFileNo, "My String 2 Here"
 
    'close the file (if you dont do this, you wont be able to open it again!)
    Close #iFileNo

*Tips : you can change the extension file :)

[VB6] Get Page Source Web Using MSXML2.ServerXMLHTTP


Deskripsi
      Get page source website using MSXML2.ServerXMLHTTP without proxy.

Howto
    Dim objHttp As Object, strText, strUrl As String
    strUrl = "http://www.target-web.com" 'url must complete
    Set objHttp = CreateObject("MSXML2.ServerXMLHTTP")
    objHttp.Open "GET", "", False
    objHttp.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.17 Safari/537.36"
    objHttp.Send ("")
    strText = objHttp.responseText
    Set objHttp = Nothing
    msgbox strText

*note : if you want to connect using proxy , you must execute command in Command Prompt :
           proxycfg -d 'if you want to direct connect access to the internet
           proxycfg -p 10.12.xx.xx:8080 "<local>" 'if you want connect using proxy.
                             -d as direct
                             -p as proxy
                             -10.12.xx.xx as proxy server
                             - <local> as local computer 
          
*tips : in VB you can create a file text , so you can can create batch file and then execute from vb.  
     

[VB6 / VB.NET ] Create OLEDB String Connection

Deskripsi
 Many newbie programmer maybe ask, how to create string connection to database (sqlserver , oracle etc) with OLEDB ? this is actually easy :D , oke let's to the tutorial !!

Howto
1. make sure that you have installed the OLEDB that accordance with the type of your database
2. Create file text in desktop , for example conn.txt
3. Rename the extention to .UDL (Microsoft Data Link)
4. Double Click to conn.udl , and go to TAB PROVIDER, your installed provider will be list in there.
5. Go to TAB CONNECTION and insert your host, username , password and don't forget allow saving password and test connection
6. if test connection success, then Save / OK
7. Right click on the conn.udl, open with NOTEPAD or another text application.
8. VOILA !! you get the connection string automatically !! (string on the red line)


[VB6][WEB] Parsing HTML


Description
What is parsing?
Parsing is another term used for "interpreting". In most cases, it means extracting information from a string. For example, you may want to extract certain parts from the HTML source of a webpage. When parsing, you will be using the basic string manipulation functions from VB. These being: Left, Mid, Right, Trim, InStr, InStrRev, Split, etc. In most cases, it's usually just a combination of InStr and Mid (avoid using the Split function if possible).
It's really hard to teach "parsing" to someone because it's entirely dependent on what data you're working with. However, after some practice, you will start to notice patterns and realize that most parsing situations call for almost the same thing.


AUTHOR
Copyright (c) 2007 - Danny Elkins (DigiRev)
http://www.DannyDotGuitar.com/digirev/
DigiRev@Hotmail.com



How To
Scenario 1: HTML

Parsing HTML
In this scenario, we will be parsing some HTML returned from a webpage. Let's say we wanted to parse, or extract, the e-mail address from a webpage. The HTML looks like this:

<html>
  <head>
    <title>Parse this</title>
  </head>
  <body>
    <strong>User@Hotmail.com</strong>
  </body>
</html>

That is probably the most basic HTML you will ever come across. It is just to get a basic idea of how a common parsing routine works. It doesn't matter how "complex" or confusing the HTML looks. The parsing process will be the same.

Step 1: Find the start!
The first step in any extraction routine, is to find the start. What is the start? It is a constant value that comes immediately before what we're looking for. Most HTML isn't constant, so it's best to keep your routine as loose, but reliable as possible. It's also common to have to modify, or re-write some parsing routines in the future as the data changes.

Anyway, what is the start that we're looking for here? The first thing that comes before the e-mail address. In this case, it would be <strong>.

WAIT!

An important thing to consider when looking for the start, is: Does that data appear anywhere else in the HTML? Does it come before or after? For example, what if the HTML looked like this?

<html>
  <head>
    <title>Parse this</title>
  </head>
  <body>
    <strong>Welcome!</strong>
    <strong>User@Hotmail.com</strong>
  </body>
</html>

What would be the start there? You would have to find the 2nd instance of <strong>. What if the HTML looked like this?

<html>
  <head>
    <title>Parse this</title>
  </head>
  <body>
    <strong>Welcome!</strong>
    <a href="#"><strong>User@Hotmail.com</strong></a>
  </body>
</html>

What would we use as the start there? We wouldn't use just <strong>, obviously, because that would bring us to "Welcome!". We would use <a href="#"><strong>. That string only appears once. So, always find the most constant, unique, string to use as the start.

Finding the start
So, how do we find the start in the HTML? VB has a nice built-in function called InStr. I did assume you have some experience with basic string manipulation functions, but if not then read the comments...(and then go learn how to use it. J).

Dim lonPos As Long
Dim strStart As String

'The start string.
strStart = "<a href=""#""><strong>"

'Find the start string.
lonPos = InStr(1, HTML, strStart, vbTextCompare)

'1 - Where we start searching in the string (from the beginning).
'HTML - The string holding the HTML.
'strStart - What we're searching for.
'vbTextCompare - Case in-sensitive search (more reliable for HTML).
'vbBinaryCompare - Faster, but it's case-sensitive.

If the search string was found, lonPos will contain the starting position. The starting position would be the < in <a href="#".

Step 2: Find the end!
Yup, now that we found the start, we find the end. It's pretty simple. The end would be what comes immediately after what we're looking for. In this example, it would be </strong>. So, all we do is use the InStr function again. Except, this time, we will supply the function with lonPos and have it start searching from there. If we searched from the beginning, it would take us to the end of "Welcome!".

Dim lonPos As Long, lonEnd As Long
Dim strStart As String, strEnd As String
Dim strEmail As String

'The start string.
strStart = "<a href=""#""><strong>"
strEnd = "</strong>"

'Find the start string.
lonPos = InStr(1, HTML, strStart, vbTextCompare)

If lonPos > 0 Then
    'Move to the end of the start string
    'which happens to be the beginning of what we're looking for. :)
    lonPos = lonPos + Len(strStart)
   
    'Find the end string starting from where we found the start.
    lonEnd = InStr(lonPos, HTML, strEnd, vbTextCompare)
   
    If lonEnd > 0 Then
        'Now, we have the starting and ending position.
        'What we do is extract the information between them.
       
        'The length of data (e-mail address) will be:
        'lonEnd - lonPos
        strEmail = Mid$(HTML, lonPos, lonEnd - lonPos)
       
        'Done!
        MsgBox strEmail
    End If
End If

A little explanation:

If lonPos > 0 Then
Checks if we found the start. If InStr didn't find it, it will return 0.

            lonPos = lonPos + Len(strStart)
            This will take us from the beginning of the start string (X<a href="#"></strong>) to the end of the start string (<a href="#"></strong>X)
            At the end of the start string is what we're looking for (the e-mail address).

            lonEnd = InStr(lonPos, HTML, strEnd, vbTextCompare)
            The search will start from lonPos and will find strEnd (</strong>).

            If lonEnd > 0 Then
            If InStr found the ending string (</strong>) then...

                        strEmail = Mid$(HTML, lonPos, lonEnd - lonPos)
                        We are using Mid to extract something from the middle of the string.
                        We start at lonPos. This starts with the first character of the e-mail address.
                        We end at lonEnd - lonPos. That will equal the length of the e-mail address (for any length-email address).

Done
As you can see, the entire process of that parsing routine was:
          Find the start (InStr)
          Find the end (InStr)
          Extract the data between (Mid)

And you know what? That is the exact same process you will use 90% of the time when you want to extract data from between two other strings.

Try this: Change up the HTML. Change the e-mail address. Change the values of strStart and strEnd in the code to match those of the HTML. Run the code. It will work regardless (as long as you got the Start and End strings right).

Since most of your parsing routines will use this method, it might be a good idea to wrap up all the code in a re-usable function.

Wrapping it up
Wrapping up the above code into a reusable function:

Private Function GetBetween(ByVal Start As Long, Data As String, _
    StartString As String, EndString As String, _
    Optional ByVal CompareMethod As VbCompareMethod = vbBinaryCompare) As String
   
    Dim lonStart As Long, lonEnd As Long
   
    '1. Find start string.
    lonStart = InStr(Start, Data, StartString, CompareMethod)
   
    If lonStart > 0 Then
        '2. Move to end of start string.
        lonStart = lonStart + Len(StartString)

        '3. Find end string.
        lonEnd = InStr(lonStart, Data, EndString, CompareMethod)
       
        If lonEnd > 0 Then
            '4. Extract data between start and end strings.
            GetBetween = Mid$(Data, lonStart, lonEnd - lonStart)
        End If
    End If
   
End Function

And if we were to use this function for this scenario, it woud be:

strEmail = GetBetween(1, HTML, "<a href=""#""><strong>", "</strong>", vbTextCompare)
MsgBox strEmail

1 - Where we start searching in the string (beginning).
HTML - The HTML we are working with.
<a href="#... - The start string.
</strong> - The end string.
vbTextCompare - Case-insensitive search (slower, but more reliable for HTML).
vbBinaryCompare - Case-sensitive search (faster, but more strict).

I hope this short little tutorial helps someone. Feel free to contact me if you have any questions/comments or suggestions on something to add to this tutorial, or suggestions for a new tutorial.

Remember the steps: Find the start, find the end, extract between.

[VB6][WEB] Get Page Source Website


Deskripsi
      Mendapatkan page source HTML dari suatu web browser

How To
1.  Project > Components > Microsoft Internet Transfer Control 6.0
2.  Drag Inet from menu toolbox into form (Name : Inet1)
3.  Drag Button from menu toolbox into form (Name : Button1)
4.  Double click button1 and Write code below


Private Sub Command1_Click()
Dim HTML As String

HTML = Inet1.OpenURL("http://www.google.com")
msgbox HTML

end sub

[VB6][DIALOG] Get Dialog Save Path


Deskripsi 
      Mendapatkan string dari dialog save path

How To 
1. Project > Component > Microsoft Common Dialog Control 6.0
2. On menu tools box in left, appear new item "Common Dialog" drag it into Form
3. Drag another item "Button" and "label" into form
4. Double click button1 and write this code


Private Sub button1_Click()
    commondialog1.InitDir = "D:\" 'setup initial directory
    commondialog1.Filter = "Excel Files 2003|*.xls|" & "Excel Files 2007|*.xlsx|" 'Create type extention file
    commondialog1.ShowSave 'Show Save Dialog
    label1.Caption = commondialog1.FileName
End Sub

5. Done, you will get path string when click save, you can use itu to another purpose.

[VB6][Excel] Write to excel file


Deskripsi
      Menulis data dari VB6 ke Excel

How To

Hirarki aplikasi excel berupa : EXCEL > BOOK > SHEET
jadi kita harus mendefinisikan ketiganya terlebih dahulu


 Private Sub Command1_Click()  
   Dim oexcel As Object  
   Dim obook As Object  
   Dim osheet As Object  
   Set oexcel = CreateObject("Excel.Application")  
   Set obook = oexcel.workbooks.Add  
   Set osheet = obook.worksheets(1)  
   'Create Header First  
   osheet.Range("A1").Value = "Test Column 1"  
   osheet.Range("B1").Value = "Test Column 2"  
   osheet.Range("C1").Value = "Test Column 3"  
   osheet.Range("D1").Value = "Test Column 4"  
   osheet.Range("E1").Value = "Test Column 5"  
  'Add data to cells of the first worksheet in the new workbook  
   osheet.Range("A2").Value = "Blah1"  
   osheet.Range("B2").Value = "Blah2"  
   osheet.Range("C2").Value = "Blah3"  
   osheet.Range("D2").Value = "Blah4"  
   osheet.Range("E2").Value = "Blah5"  
   On Error GoTo localerr  
    'Save the Workbook and Quit Excel  
    oexcel.DisplayAlerts = False  
    obook.SaveAs "D:\myfirst_extract.xlsx"  
    oexcel.Quit  
    MsgBox "Extract to Excel Complete, file save in :" & "D:\myfirst_extract.xlsx"  
   Exit Sub  
   localerr:  
   If Err.Number = 1004 Then MsgBox "Failure to write file because file in use, please close first!",  vbCritical, "ERROR"  
 End Sub  

Note:

     *extensi untuk menyimpan bisa diganti sesuai versi excel yang diinginkan.
     *jangan lupa untuk selalu close excel setelah write ( oexcel.quit )

[VB6] CRUD


Deskripsi
     VB6 agar dapet melakukan Create , Read , Update , Delete Record.

How To
1. Add References
2. Create Variable Global untuk Connection dan Recordset
3. Create Connection to Database (Use UDL File or use Connection String)
4. Query (Insert, Retrieve , Update).

*Add Refferences
  Project>Refferences>Microsoft Active X Data Object 2.7 Library
  or you can add manual in path :
  C:\Program Files\Common Files\system\ado\msado.tlb

*Create Variable Global for connection and recordset (optional) in MODULE
   
Public ConnectSQLServer As ADODB.Connection  'connection SQL Server
Public ConnectORAServer As ADODB.Connection  'connection ORA Server
Public RSSQLSERVER ' for recordset untuk aplikasi - sql server
Public RSORASERVER ' for recordset untuk aplikasi - oracle



* Create UDL File
   untuk membuat UDL file , cukup buat file text kemudian di rename extensinya dari .txt menjadi .udl, kemudian klik 2x file UDL tersebut , pilih provider yang menggunakan OLE DB (SQL Server / Oracle / Access) yang akan digunakan.
  pilih tab connection kemudian isi data-datanya dan checklist allow saving password.

* Create Connection to Database
  
Public Function ConnectDatabaseSQLServer()

' Fungsi untuk melakukan koneksi ke database SQL server

On Error GoTo LocalErr

    Set ConnectSQLServer = New ADODB.Connection

    ConnectSQLServer.Open "FILE NAME=" & App.Path & "\SQLServer.udl"

    Exit Function

  

LocalErr:

    Screen.MousePointer = vbDefault

    If Err.Number = -2147467259 Then

        MsgBox "Connection failed, please check data link properties in path SQLServer.udl !," & Chr(13) & _

        "Or SQL Server not running. Open SQL Server service manager, server name and services must correct.", vbCritical, "Error Connection"

        Exit Function

    Else

        MsgBox Err.Number & Chr(13) & Err.Description, vbCritical + vbOKOnly, "Error Connection"

    End If

End Function





  
' Fungsi untuk melakukan koneksi ke database oracle
Public Function ConnectDatabaseORAServer()
On Error GoTo LocalErr

    Set ConnectORAServer = New ADODB.Connection

    ConnectORAServer.Open "FILE NAME=" & App.Path & "\ORAServer.udl"

Exit Function

  

LocalErr:

    Screen.MousePointer = vbDefault

    If Err.Number = -2147467259 Then

        MsgBox "Connection failed, please check data link properties in path ORAServer.udl !," & Chr(13) & _

        "Or ORACLE Server not running. Open Oracle Server service manager, server name and services must correct.", vbCritical, "Error Connection"

        Exit Function
    Else
        MsgBox Err.Number & Chr(13) & Err.Description, vbCritical + vbOKOnly, "Error Connection"

    End If

End Function






Query (Insert)
  
public function insertDataSQLSERVER()
  ' Insert no need recordset to accomodate data record, because no data to retrieve
   Dim strsql As String

   strsql = "insert table (blah1,blah2) values ('A','B')"
      

   ConnectSQLServer.BeginTrans
   ConnectSQLServer.Execute strsql
   ConnectSQLServer.CommitTrans
end function







Query (Retrieve)
  
public function retrieveDataSQLSERVER()
   Dim strsql As String
   Dim RSSQLSERVER As ADODB.Recordset
  
   ' Create Object Recordset 
   Set RSSQLSERVER = New ADODB.Recordset
   RSSQLSERVER .CursorLocation = adUseClient

   strsql = "select * From table where blah1 = 'A'"
   ' Check Status Record set , already Open or Still Close
   If RSSQLSERVER .State <> adStateClosed Then RSSQLSERVER .Close
   'FILL Recordset with data from Database 
   RSSQLSERVER .Open strsql, ConnectSQLServer, adOpenKeyset, adLockOptimistic
   'set recordset to grid
   Set yourgrid.DataSource = RSSQLSERVER


   'Check Record Count
   if RSSQLSERVER.recordcount > 0 then
         msgbox "total record : " & RSSQLSERVER .recordcount
         'sample test retrive some record
         ' syntax format :  ActiveRecordset!Field
         msgbox RSSQLSERVER !blah1
   else
         msgbox "No Record"
   endif

end function







Query (Update)
  
  
public function insertDataSQLSERVER()
 ' Update no need recordset to accomodate data record, because no data to retrieve
   Dim strsql As String

   strsql = "update table set blah1='C' where blah2='B' "
      
   ConnectSQLServer.BeginTrans
   ConnectSQLServer.Execute strsql
   ConnectSQLServer.CommitTrans
end function




Note :
   Semua query berlaku untuk semua database dari Access , SQL SERVER dan Oracle yang terpenting hanya pada koneksi Provider Databasenya (Use UDL File or Connection String).

* Terminate Connection or Recordset
   simple ! just add method .close
   for example (based on tutorial above and your variable) :
   ConnectSQLServer.close // closing connection
   and
   RSSqlServer.close // closing recordset

   don't forget your variable must be already as an object ! 

[VB6] Textbox hanya menerima input angka


Deskripsi
     Textbox hanya menerima input angka , character tidak diperbolehkan

How to :


1. Buat object textbox

2. klik 2x, ganti event ke Keypress

Ikuti contoh code seperti dibawah ini :


Private Sub Text1_KeyPress(KeyAscii As Integer)


   Dim strKey As String
   strKey = "0123456789"
   If KeyAscii > 26 Then
      If InStr(strKey, Chr(KeyAscii)) = 0 Then
         KeyAscii = 0
         Exit Sub
      End If
   End If



End Sub