Labels

Wednesday, 10 October 2012

VB script programs

Listing out some of the useful programs which would be asked during interviews:

#1 - '' Program to find out Drive and File name from the Given file path
Public Function getFname(ByVal fname)

    firstSlash = InStr(1,fname,"\")
    lastSlash = InStrRev(fname,"\")
    Msgbox "Filename:"& vbTab & Mid(fname,lastSlash+1)
    Msgbox "Drive:"& vbTab & Mid(fname,1,firstSlash-1)

End Function

++ Bonus points: Mid function helps lot in scripting, so get familiar with it!

#2 - '' String reverse without using built-in function
Function strRev(Byval input_str)
   sLen = Len(input_str)
   sRev = ""
   For i=0 to sLen-1
       print Mid(input_str, sLen - i,1)
        sRev = sRev & Mid(input_str, sLen - i,1) 
   Next
   msgbox sRev
End Function

#3 - '' String length without using built-in function
Function strLength(ByVal str)
    i = 1
    While (Mid(str,i,1)) <> ""
        i = i + 1
    Wend
    Msgbox "String length--"&i-1
End Function

#4 - '' To get Unique alphanumeric string for the given length
Public Function randomStr ( ByVal strLen)
   Const Str = "abcdefghijklmnopqrstuvwxyz0123456789"
   newStr = ""

    For i=1 To strLen
        newStr = Mid (Str, RandomNumber(1,len(Str)),1) &  newStr
    Next
   msgbox newStr &" of lenth " & strLen
End Function

++ Bonus points: If you want to get only random string then define Constant Str with a-z characters. Similary if you need only random numbers, specify Const Str with 0-9.

'' Calling the above functions
strRev("sundar")
strLength("sundar")
getFname("C:\Users\Sundar\Documents\UNIX1.txt")
randomStr(5)

No comments:

Post a Comment