Sunday, December 27, 2009

Excel VBA: Find And Replace String Using VBA Code

There are several ways to replace string using VBA code,  by looping each cell or by using VBA Replace function.

Let's say that we want to replace "Macrosoft Excel" with "Microsoft Excel" from A1 through A500.

This first example loops from A1 through A500 and replace "Macrosoft Excel" with "Microsoft Excel".
 
Sub Find_Replace1()
    Dim I As Integer
    Dim SFind As String
    Dim SReplace As String
    
    SFind = "Macrosoft Excel"
    SReplace = "Microsoft Excel"
    For I = 1 To 500
        If Cells(I, 1).Value = SFind Then
            Cells(I, 1).Value = SReplace
        End If
    Next I
End Sub

The following example is more efficient than previous example:

Sub Find_Replace2()
    Dim SFind As String
    Dim SReplace As String
    
    SFind = "Macrosoft Excel"
    SReplace = "Microsoft Excel"

    Range("A1:A500").Replace _
        What:=SFind, Replacement:=SReplace, _
    LookAt:=xlWhole, MatchCase:=False
End Sub

If you to make the search case sensitive you can change the MatchCase property to true. And also if you want to replace data that contain part of the searched data you can change the LookAt property to xlPart.

Related posts:
---
If you like posts in this blog, you can to support me :)

Saturday, December 12, 2009

Excel VBA: Date Calculations

To add or subtract an interval (a relative date) from a date, we could use DateAdd function. The syntax is:

DateAdd(interval, number, date)
The DateAdd function syntax has these named arguments:
Part Description
interval Required. String expression that is the interval of time you want to add.
number Required. Numeric expression that is the number of intervals you want to add. It can be positive (to get dates in the future) or negative (to get dates in the past).
date Required. Variant (Date) or literal representing date to which the interval is added.


Settings
The interval argument has these settings:
Setting Description
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week
h Hour
n Minute
s Second

The following example add two months to October 31, 2009:

MsgBox DateAdd("m",2,"31-Jan-09"))

Related posts:

---
If you like posts in this blog, you can to support me :)