Sunday, March 14, 2010

Validate Date in VBA

Sub Feed_Check_Date_Function()

‘ Date is within the Valid Range
Check_Date “2011-09-01?, “2011-09-10?, “2011-09-01?

‘ Date is NOT within the Valid Range
Check_Date “2011-09-01?, “2011-09-10?, “2011-09-21?

End Sub

Function Check_Date(ByVal StartDate As Date, ByVal EndDate As Date, ByVal DateTobeChecked As Date)

If DateDiff(“d”, StartDate, DateTobeChecked) <> 0 Then
MsgBox “Enter a correct date!!!!!”
End If

End Function

Check Column Exist in Excel

'Check the column exist in Excel File. In Fnd string pass the Column heading text.

Function CheckColumnExist(Fnd As String) As Boolean
'Check the column exist in Excel File.
CheckColumnExist = False
Set r1 = Cells.Find(What:=Fnd, _
After:=ActiveCell, _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not r1 Is Nothing Then
CheckColumnExist = True
End If
End Function

To get windows temp directory path

'This private method is used to get windows temp directory path

Private Function GetTmpPath()

Dim sFolder As String ' Name of the folder
Dim lRet As Long ' Return Value

sFolder = String(MAX_PATH, 0)
lRet = GetTempPath(MAX_PATH, sFolder)

If lRet <> 0 Then
GetTmpPath = Left(sFolder, InStr(sFolder, _
Chr(0)) - 1)
Else
GetTmpPath = vbNullString
End If

End Function

To Find the Last Used Row in Excel

Function FindLastRow() As String
Dim LastRow As Long
If WorksheetFunction.CountA(Cells) > 0 Then
'Search for any entry, by searching backwards by Rows.
LastRow = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
FindLastRow = LastRow
End If
End Function

To Find the Last Used Column in Excel

Function FindLastColumn() As String
Dim LastColumn As Integer
If WorksheetFunction.CountA(Cells) > 0 Then
'Search for any entry, by searching backwards by Columns.
LastColumn = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
FindLastColumn = LastColumn
End If
End Function