Archive for the ‘VBA’ Category


Reverse geocoding is the process of taking a set of GPS coordinates and turning it into the nearest available address.
Browsing through the net, I found VBA code on many websites to get GPS coordinates(latitude & longitude) from a location address but found it really hard to get a reverse geocoding in VBA.
It can be achieved using following Google API:
http://maps.googleapis.com/maps/api/geocode/json?latlng=-33.856098662,150.996315097333&sensor=false

It will return JSON, that can be parsed to get the nearest available location.
e.g.


Function GEOAddress(dblLatitude As Double, dblLongitude) As String
         
    Dim strJSON         As String
    Dim strAddress      As String
    Dim lngTemp         As Long
    Dim objXml          As Object
    Dim strUrl          As String
        
    strUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" & dblLatitude & "," & dblLongitude & "&sensor=false"
    Set objXml = CreateObject("Microsoft.XMLHTTP")
    With objXml
        .Open "GET", strUrl, False
        .send
        strJSON = .responseText
    End With
    Set objXml = Nothing
        
    lngTemp = InStr(1, strJSON, "formatted_address")
    strAddress = Mid(strJSON, lngTemp + 22, InStr(lngTemp, strJSON, """,") - (lngTemp + 22))
    GEOAddress = strAddress
    
End Function

Happy Coding 🙂

Advertisements

Problem Statement: I have a database of employees where I store information about each person. I wish to have a picture of the employee in my database that I want to retrieve when I select an employee ID. Solution: I am sharing a VBA code that saves the file in SQL server table in binary format. When the file is retrieved, it can be done in original format. Let’s say I’ve a table Employee, it has two columns ID (Datatype: int) and Image (Datatype: varBinary(Max)). Code to store an image as binary type: (more…)


In my experience I have come across numerous people who so wish that their charts are ‘Interactive’. I’m sure many of you would like to select a data point on your chart and let it act as a selection for sort of a drill-down. Doing this, although not impossible in Excel, requires sound understanding of Class Modules and chart events. I have tried to create a small example to illustrate this.

Problem Statement:I have  data for daily site views for USA, Canada and the rest of North America. While there is a top chart that shows the cumulative counts, I would like to select a data point on the chart and see a detailed view for it as below.

Chart Event Example

Chart Event Example

(more…)

Opening URL @ new tab in Internet Explorer: VBA

Posted: September 11, 2013 by Theodoulus in Excel, General Tips, VBA
Tags:

Problem Statement: Suppose, we have an array of URLs and we need to open them one by one. By looping over all the URLs on the same tab at internet explorer, we need to check the internet explorer is in LOADED or LOADING state. If the explorer is in loading state, it may give an error. And by default, the URL will be opened on the same tab.

So the process of opening URL on the same tab will be lengthy in terms of Coding, and processing time.

Solution:

We can use different tabs of the Internet Explorer so that we would not have to check the READYSTATE and to REFRESH the tab again and again. The example is given below:

Option Explicit

Sub OpenURLOnNewTab()

    Dim lngC As Long
    Dim strUrl  As String
    Dim ieObj   As InternetExplorer

    Set ieObj = New InternetExplorer
    ieObj.Visible = True
    strUrl = "https://usefulgyaan.wordpress.com/"       'We have taken one URL but you can take an array of URLs

    For lngC = 1 To 100
        ieObj.Navigate2 strUrl, 2048            '2048 is to open the URL on the new tab
    Next lngC

End Sub

While Preparing an Excel Dashboard one needs to handle a lot of hiding and unhiding of Sheets for various users. For Devloper all sheets should be unhidden and for user some of them should visible. We need different views of one workbook for different people developer, user, admin, etc.
We can handle this with using a Custom View property of the workbook with VBA

ActiveWorkbook.CustomViews.Add Viewname, PrintSettings(value True/False), RowColumnSettings(value True/False)

(more…)

Adding Metadata to a Worksheet:CustomProperties

Posted: July 29, 2013 by kulshresthazone in Excel, VBA
Tags:

Want to keep some information a bit out of reach of the user or you want to keep some information for your code support, away from general user.

One way of storing information is using constants in your code. Now, suppose you have multiple sheets and you want to associate the constant’s values with specific sheets. Then, in place of creating a mapping of sorts or creating multiple constants for each sheet, you can make use of adding metadata to a worksheet.
To Add:

Worksheets(WorksheetName).CustomProperties.Add Name:=PropertyName, Value:= SomeValue

To Read:

Worksheets(WorksheetName).CustomProperties.Item(PropertyIndex).Value

Happy Coding…  :)


We protect a worksheet so that it can not be modified and this protection applies to VBA operations and user actions both. Some VBA operations like pasting data cannot be done on a protected worksheet. Now to perform these operations on that sheet we need to unprotect it, do the operations and then protect it again.
e.g.

Sub EditSheet()

    ThisWorkbook.Worksheets("Sheet1").Unprotect Password:="1234"
    ' Code to perform some operations to edit the sheet
    ThisWorkbook.Worksheets("Sheet1").Protect Password:="1234"

End Sub

Although the above technique works but we need to wrap our code between Unprotect and Protect statements in every procedure that performs some operations on the protected sheet. So if we need to protect our worksheet from user actions only then there is a better way of doing it. (more…)

VBA Trick of the Week :: Hiding Members of Enum

Posted: July 19, 2013 by Transformer in Excel, VBA
Tags: , ,

If you want to prevent a member of Enum from being displayed in VB editor’s intellisense then it can be done by prefixing them with ‘_’ and then putting them in square brackets.
e.g.

Enum Role
     AVP
     Manager
     Analyst
     [_HideMe]
End Enum

Enum

In the above image it can be seen that [ _HideMe] is not displayed in intellisense.

Text Comparison: Option Compare Text

Posted: July 12, 2013 by kulshresthazone in Excel, Outlook, Powerpoint, VBA
Tags: ,

If we compare text in VBA Code then “B” is not equal to “b” since there ASCII codes for both these characters are different. However we can force Excel code to compare text on the basis of  Text not on their Binary values.
Make use of  Option Compare Text on the very First line of the Code module. It will force VBA to compare Text in Text mode not in Binary mode. By Default Text comparison is done in Binary mode.

If we don’t use Option Compare Text then
“B”<>”b”
If we make use of Option Compare Text then
“B”=”b”

Happy Coding…


Converting a Range to Recordset is a very painfull process. Currently the process which we follow is establishing a connection and then firing a Query to get the values in to a Recordset.
But now we can make a new and better approach using the Range.Value() property.
This is a better way to move data from one workbook to another without making use of the Clipboard.


Sub Test()

        Dim xlXML             As Object
        Dim adoRecordset      As Object
        Dim rng               As Range

        Set rng = ActiveSheet.Range("A1:D20")
        Set adoRecordset = CreateObject("ADODB.Recordset")
        Set xlXML = CreateObject("MSXML2.DOMDocument") 
        xlXML.LoadXML rng.Value(xlRangeValueMSPersistXML)
        adoRecordset.Open xlXML

End Sub

This adorecordset will hold the range in the form of recordset and one make use of this in the way it is required.
Happy Coding….   😉