Want to become an expert in VBA? So this is the right place for you. This blog mainly focus on teaching how to apply Visual Basic for Microsoft Excel. So improve the functionality of your excel workbooks with the aid of this blog. Also ask any questions you have regarding MS Excel and applying VBA. We are happy to assist you.

How to use Find and replace function in VBA

Today I'm going to explain you how to use another very important excel sheet function in VBA. It is find and replace function. If you are an excel user, surely you may have use this function manually. But today I'm going to explain you how to use this excel sheet function in a VBA program/macro.

In Excel 2013, you can find this function (Find & Select) under "Editing" section of "Home" Tab. If you are using any other version, you will able to find it in a similar place.


If you click on the arrow head, this kind of dropdown list will appear.


Then click on the "replace". Then you will get this pop up window.


You may have use this window before to find and replace words in your excel sheets. But today I'm going to explain you how to use this function in a VBA program. Let's use below sample paragraph to test our code.

So let's try to replace word "excel" with word "Word".

Following is the equivalent VBA code to do the "find and replace" worksheet function.

Sub FindReplace()

Dim SearchText As String
Dim ReplacementText As String

SearchText = "excel"
ReplacementText = "Word"

Worksheets("Sheet1").Cells.Replace What:=SearchText, Replacement:=ReplacementText, LookAt:=xlPart, MatchCase:=False

End Sub

You will get this result after running the above code.


However there is a one small problem with above code. Consider the following example.


If we run the macro for above sheet, You will notice that word "excellent" will change to "Wordlent".

Because of that, this find and replace code has limitations. If you need to avoid above type of errors, then you will need advance solution than this.

How to scroll a web page number of pixels

In this post, I'm going to explain how to scroll a web page number of pixels you need. There are various types of websites. Lot's of these websites have an option to search for information. Normally there is a text box to input search word or phrase and then there is a "search" button to click. When we search for something in a website, some websites list the results in number of pages. So we need to go to each page to find the information.

But some websites do not show results in several pages. Instead they show all the results in one page. But if there are lots of results then these websites only load small part of the complete result. They loads the other data part by part while we scroll through the page.

So if we need to write a program to get data automatically from a website where results are shown in different pages, we can do that by commanding the program to navigate to each page. For some websites we can do this by just changing the number in the address of page.

But how we collect the data from a website which loads the data only when we scroll. Here is the solution. We can write a code to scroll a web page number of pixels. You can use below code for that. It will scroll a page 100 pixels.

'Scroll web page 100 pixels down
objIE.Document.parentWindow.scrollBy 0, 100

But there will be a limit of pixels you can scroll at once. For an example if you command the page to scroll for 100000 pixels, it won't do that. It will only scroll a amount, what  it normally scroll per one time when do manually. However if you want to scroll long range, you can do that by commanding the page to scroll several times like this.

'Scroll the page 10 times
For i = 1 To 10
    objIE.Document.parentWindow.scrollBy 0, 100000 * i
    Application.Wait (Now + TimeValue("0:00:03"))
Next i

Please note that objIE in above examples refers to "InternetExplorer.Application" object.

Change attributes of controls inside VBA userforms in easier way

Sometimes we need to use set of similar controls when developing applications with userforms. For an example we may need to use set of labels, dropdowns or textboxes etc inside a vba userform. If we have similar set of controls like that, then there are situations we may need to change the values or visibility of the controls according to the various logics and conditions.

Let's look at the following example.

Here we have 4 labels and 4 combo boxes. Sometimes we need to control the attributes of these controls or change the values of controls. If we give random names for each control then we need to control their attributes one by one or we need write one line per each control to change their values. But if we have similar set of controls and we name them simila manner, then we can change the attributes or values of the controls using a For Next loop. So for above example we can name lables like lblCycle1, lblCycle2, lblCycle3 and lblCycle4. And we can name combo boxes as cboScore1, cboScore2, cboScore3 and cboScore4. Then we can change the attributes as follows.

Dim i as Integer
Dim NumberOfCycles as Integer

For i = 1 To NumberOfCycles
    UserForm2.Controls("lblCycle" & i).Visible = True
    UserForm2.Controls("cboScore" & i).Visible = True
Next i

In above example, variable "NumberOfCycles" equal to how many pairs of labels and combo boxes we need to show in userform2.

Add Button To Excel Worksheet

    We often need to add buttons to worksheets. We can use buttons for many things. Triggering a macro and navigate through worksheets are two very common use of buttons. Sometimes appearance of the button is not very important. But there are situations where we need to give higher concern for its appearance. Specially when creating dashboards. Because it is very important to give professional look to your dashboard.

    There are several types of buttons available. In this post I will show you how to add Form Control Button to your excel worksheet. Lots of people use this button to trigger macros. However I don't recommend these buttons for dashboards. Because we can't even change the color of these buttons to match with our dashboards. Also we can't change the font color of the button. But this type of buttons are very useful if you want to trigger macros. Because these buttons are compatible with all excel versions. Specially with Mac versions. So if you use this kind of button you can assure that your users will able to run macros by clicking the button from any OS and any Excel version.

    If you want to add a form control button to your worksheet, first go to the Developer tab of your excel application. If Developer tab is not visible in your Excel application,  below post will explain you how to do that.

How to show the Developer tab

After go to the developer tab, click on the insert menu. Then you will see this kind of icons.

Then click on the Button (Form Control). Then your mouse pointer will look like this.


Then click somewhere on the worksheet and drag like below to form small rectangle.

Then release the mouse. You will see this kind of pop up window.

This pop up window helps you to assign macros directly when you create the button. In this case no macros listed because there are no macros in opened files. So you can click OK to create the button without assigning any macro. Then you can assign macro later if you need. However if you have macros in your files, then this pop up will look like below.

So there are two macros in the files. One is MyFirstMacro and other is MyMacro. So if you need to assign any of these macros to your button, first click on the macro name and then click on the OK button.

When you click OK button, form control button will created in the worksheet like this.

Then you can edit text and also you can change font type, font size etc. But you can not change the color of font or color of the button.

Create Excel Timer Using VBA

    Today I'm going to show you how to create a Excel Timer. First we need to add two buttons to the excel sheet. One is to start timer. Other one is to stop the timer. And we need to reserve one cell to display the value. Here is an example interface.


We can give it nice look by removing grid-lines.

Now add new module in the VBA editor of your workbook. And add below code to it.

Public StopMacro As Boolean


Sub StartTimer()

StopMacro = False

Dim WS As Worksheet

Set WS = Worksheets("Sheet1")

Dim StartTime, timeNow

StartTime = Now

Do Until StopMacro = True
    DoEvents
    timeNow = Now
    WS.Range("F8").Value = Format(timeNow - StartTime, "hh:mm:ss")
Loop

End Sub


Sub StopTimer()

StopMacro = True

End Sub

Then assign StartTimer macro to start button and StopTimer macro to Stop button. I think you will able to understand this code easily. However I will explain few important points. In this program we have declared one public variable of type Boolean. We use that variable to detect when user click stop button. So when user click stop button, value of StopMacro variable become true. Then it is detected in do until loop.

In this program we used inbuilt Excel function call Now which returns date and time.

Value entering cell and format of the value is given by below line of code.

WS.Range("F8").Value = Format(timeNow - StartTime, "hh:mm:ss")

Also it is very important to use DoEvents within the do until loop. Otherwise user will not get any chance to click on the stop button and loop will become infinite loop.

Do Until StopMacro = True
    DoEvents
    timeNow = Now
    WS.Range("F8").Value = Format(timeNow - StartTime, "hh:mm:ss")
Loop



And this is how timer shows the time.


Pause Program Execution In VBA - Sleep and Wait Functions

Sometimes we need to pause the execution of our program for a specific time. In VBA, we can use a few methods to do this. VBA Wait method and Sleep functions are two popular methods used by VBA developers.

Why you need to use Sleep or Wait in VBA

  • Sleep or wait method let other applications complete their processes.
    For example if you are developing a web scraping program, the Internet explorer should get sufficient time to load the webpage.
  • To get input from users
    Sometimes you may want to let the user input data to a VBA form before completing the rest of the process.
  • Let the user to use another program manually
    Using VBA we can automate various applications like MS Word, Powerpoint, Internet Explorer etc. But there are third party applications which we can not automate using VBA. In such cases we can use sleep function or wait method and let the user complete the middle process manually. Once that part is completed the macro can resume from that point.

Now Let’s look at how to use these two methods in VBA programs.

This is how to use the Wait method to pause a macro for 10 seconds.

Sub WaitForTenSeconds()

Application.Wait (Now + TimeValue("0:00:10"))

End Sub

However Sleep is a windows function. It is not a VBA function like Wait. So you have to declare the name of the API at the top of your module. So this is how you can pause the program for 10 seconds using the Sleep function.

#If VBA7 Then
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal duration_Milliseconds As LongPtr) 'For 64 Bit Systems
#Else
    Public Declare Sub Sleep Lib "kernel32" (ByVal duration_Milliseconds As Long) 'For 32 Bit Systems
#End If

Sub WaitForTenSeconds()

Sleep 10000     'You need to input the time in milliseconds

End Sub

Here is a question lot of people get

Should I use a VBA sleep or Wait

First of all Sleep is not a VBA function. Sleep is a windows function. You should import it from Kernel32.dll

What is a Kernel
The kernel is the lowest level of any operating system. And it is the core or the central component of an operating system. It starts when the computer starts and keeps loaded until it is turned off. kernel manages the CPU resources, memory resources and processes of the computer. It also contains device drivers. Therefore when you do networking or use the file system, they all go through the kernel.

So functionality of both of these methods are the same. However Wait is more accurate than Sleep. But Sleep is more flexible as you can give the time in milliseconds. If you use Wait method, shortest time you can pause the program is 1 second.
Also there is another important aspect you need to consider. That is, if you use sleep or wait in VBA programs, you will notice that these functions suspend all other activities of Microsoft Excel. You can't even click in the excel sheets. However, you can work in other applications.

But sometimes you may need to pause the program for a longer time. And while the program is paused, you may need to do some work in the Excel application like typing, navigating between sheets, scrolling through the sheets etc. We don't often need this. But it may be needed specially in web scraping applications. Because sometimes users need to analyze gathered data while the web scraping program runs. However there is no VBA function or VBA method available for this. So we need to create our own custom pausing method. Read this post if you want to know how.

How to pause a macro for specific time

VBA Web Scraping - Identifying Disabled Dropdowns

In this post I will explain how to identify a disabled drop-down.

Think we need to gather data from drop downs of list of web pages. Assume list of urls are in column A of an Excel worksheet and we need to put the value of the drop-down to a column B.

First we need to find a disabled drop down and compare it's HTML code with HTML code of normal drop-down to find something unique part for disabled ones.

For an example here is a HTML code of a normal drop down.

<select start="1" min="1" step="1" ptext="Quantity: " name="tmp" class="drp qty">

And below is a HTML code of the disabled drop down.

<select start="1" min="1" step="1" ptext="Quantity: " disabled="disabled" name="tmp" class="drp qty">

So now we can see that disabled="disabled" is unique for HTML codes of disabled drop downs. Because of that we can use Instr function to distinguish disabled drop downs.

DisableCheckingString = objIE.document.getElementsByClassName("drp qty")(0).outerhtml

If InStr(1, DisableCheckingString, "disabled=""disabled", vbTextCompare) > 0 Then
    WS.Range("B" & i).Value = "Drop-down disabled"
End If
   
So here is a full code of an example.

Dim WS As Worksheet

Dim QuantityString As String
Dim DisableCheckingString As String
Dim url As String

Set objIE = CreateObject("InternetExplorer.Application")

Set WS = ActiveSheet

objIE.Top = 0
objIE.Left = 0
objIE.Width = 800
objIE.Height = 600

objIE.Visible = True

'find last row
Lastrow = WS.Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row

For i = 1 To Lastrow

    url = WS.Range("A" & i).Value
   
    If WS.Range("A" & i).Value <> "" Then

        objIE.Navigate (url)
       
        Do
        DoEvents
        Loop Until objIE.readystate = 4
       
        Application.Wait (Now + TimeValue("0:00:03"))
       
        QuantityString = objIE.document.getElementsByClassName("drp qty")(0).innerText
       
        DisableCheckingString = objIE.document.getElementsByClassName("drp qty")(0).outerhtml
       
        WS.Range("B" & i).Value = QuantityString
               
        'Distinguish disabled ones
        If InStr(1, DisableCheckingString, "disabled=""disabled", vbTextCompare) > 0 Then
            WS.Range("B" & i).Value = "Out of Stock"
        End If
   
   
    End If

Next i

objIE.Quit

MsgBox "Completed!", vbInformation, ""

Contact Form

Name

Email *

Message *