Home » excel » excel vba – MSWinsock.Winsock event handling in VisualBasic

excel vba – MSWinsock.Winsock event handling in VisualBasic

Posted by: admin March 9, 2020 Leave a comment


I’m trying to handle Winsock_Connect event (Actually I need it in Excel macro) using the following code:

Dim Winsock1 As Winsock 'Object type definition

Sub Init()
    Set Winsock1 = CreateObject("MSWinsock.Winsock") 'Object initialization
    Winsock1.RemoteHost = "MyHost"
    Winsock1.RemotePort = "22"

    Do While (Winsock1.State <> sckConnected)
        Sleep 200
End Sub

'Callback handler
Private Sub Winsock1_Connect()
    MsgBox "Winsock1::Connect"
End Sub

But it never goes to Winsock1_Connect subroutine although Winsock1.State is “Connected”.
I want to use standard MS library because I don’t have administrative rights on my PC and I’m not able to register some custom libraries.
Can anybody tell me, where I’m wrong?

How to&Answers:

Are you stuck using MSWinsock?
Here is a site/tutorial using a custom winsock object.

Also… You need to declare Winsock1 WithEvents within a “Class” module:

Private WithEvents Winsock1 As Winsock

And finally, make sure you reference the winsock ocx control.
Tools -> References -> Browse -> %SYSEM%\MSWINSCK.OCX


Documentation about Winsock Control:
Example here:

My short example with event handling in VBscript:

Dim sock
Set sock = WScript.CreateObject("MSWinsock.Winsock","sock_")
sock.RemoteHost = "www.yandex.com"
sock.RemotePort = "80"

Dim received
received = 0

Sub sock_Connect()
    WScript.Echo "[sock] Connection Successful!"
    sock.SendData "GET / HTTP/1.1"& vbCrLf & "Host: " & sock.RemoteHost  & vbCrLf & vbCrLf
End Sub

Sub sock_Close()
    WScript.Echo "[sock] Connection closed!"
End Sub

Sub sock_DataArrival(Byval b)
    Dim data
    sock.GetData data, vbString
    received = received + b
    WScript.Echo "---------------------------------------"
    WScript.Echo " Bytes received: " & b  & " ( Total: " & received & " )"
    WScript.Echo "---------------------------------------"
    WScript.Echo data
End Sub

'Wait for server close connection
Do While sock.State <> 8
    rem WScript.Echo sock.State
    WScript.Sleep 1000

Output will be:

cscript /nologo sockhttp.vbs

[sock] Connection Successful!
 Bytes received: 1376 ( Total: 1376 )
HTTP/1.1 200 Ok
Date: Mon, 08 Dec 2014 15:41:36 GMT
Content-Type: text/html; charset=UTF-8
Cache-Control: no-cache,no-store,max-age=0,must-revalidate
Expires: Mon, 08 Dec 2014 15:41:36 GMT