Showing posts with label Excel VBA. Show all posts
Showing posts with label Excel VBA. Show all posts

Saturday, December 5, 2020

Reset VBA Password

 Reset VBA Password

1) Rename XLSM to Zip extension.

2) Don't extract this zip, but Open the file with 7-Zip

3) Copy file from xl -> vbaProject.bin (you can drag and drop from 7-Zip).

4) Don't clse zip application

5) open vbaProject.bin with HexEditor and find for "DPB=" and replace it with "DPx", save the file and move back to xl folder in the zip file.

6) Rename zip with XLSM now, and open the file.


if prompted to "Continue Loading Project", click Yes. If prompted with errors, click OK.Press Alt+ F11 to open the VBA editor.

While press it will show error “Unexpected error (40230)”, just click OK (6 or 7 times) until it goes away.

Then it will open Automatically

Then set a new password and save the file...

Monday, November 30, 2020

Email with Attachment using Excel VBA

One of my friend ask me, is it possible to send multiple emails with attachments using Excel VBA. I said YES, everything is possible. Below is just small code that can help you to do it.


Happy Coding :)

Monday, July 27, 2020

Create QR-Code with VBA

Function to add QR-Code as image in your file.


Function Insert_QR(codetext As String)
	Dim URL As String, MyCell As Range

	Set MyCell = Application.Caller
	URL = "https://chart.googleapis.com/chart?chs=125x125&cht=qr&chl=" & codetext
	On Error Resume Next
	  ActiveSheet.Pictures("My_QR_" & MyCell.Address(False, False)).Delete 'delete if there is prevoius one
	On Error GoTo 0
	ActiveSheet.Pictures.Insert(URL).Select
	With Selection.ShapeRange(1)
	 .PictureFormat.CropLeft = 10
	 .PictureFormat.CropRight = 10
	 .PictureFormat.CropTop = 10
	 .PictureFormat.CropBottom = 10
	 .Name = "My_QR_" & MyCell.Address(False, False)
	 .Left = MyCell.Left + 25
	 .Top = MyCell.Top + 5
	End With
	Insert_QR = "" ' or some text to be displayed behind code
End Function


Excel To PDF with VBA

 

Sub ConvertExcelToPDF()
'Export Single Sheets
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="TrainingDeo",      OpenAfterPublish:=True

'Export Multiple Sheets
Sheets(Array("RemovingDuplicates", "HideUnhide", "ExportToPDF")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="TrainingDemo2", OpenAfterPublish:=True

Sheets("ExportToPDF").Select
Range("A1").Select
End Sub


Reference Code at YouTube

Wednesday, March 20, 2019

Replace "Tab Character" in Excel Active Sheet

TAB - horizontal tab Decimal Value is 9


Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim lRow As Long
Dim lCol As Long
   
    'Find the last non-blank cell in column A(1)
    lRow = Cells(Rows.Count, 1).End(xlUp).Row
   
    'Find the last non-blank cell in row 1
    lCol = Cells(1, Columns.Count).End(xlToLeft).Column

For i = 1 To lRow
    For j = 1 To lCol
        t = Cells(i, j).Value
        If (Len(t) > 0) Then
            If (Asc(Left(t, 1)) = 9) Then
                str1 = Mid(t, 2, Len(t))
                Cells(i, j).Value = str1
            End If
        End If
    Next
Next

End Sub

Tuesday, January 1, 2019

Get Height and Width of a Cell in Excel

Private Sub Worksheet_Activate()
    Dim getHeight As Single
    Dim getWidth As Single
   
    For i = 1 To 10
        getHeight = Range("A" + Trim(Str(i))).Height
        getWidth = Range(Chr(65 + i) + "1").Width
     
        Me.UsedRange(i, 1) = "Row  cm : " + Str(Round((getHeight / 72) * 2.54, 2))
        Me.UsedRange(1, i + 1) = Chr(65 + i) + "1 :" + Str(Round((getWidth / 72) * 2.54, 2))
     
    Next
End Sub

Saturday, February 24, 2018

Download URL Link using VBA

'Add module in VBA, Copy and Paste following code into it.

Option Explicit

Private Declare Function URLDownloadToFile Lib "urlmon" _
Alias "URLDownloadToFileA" (ByVal pCaller As Long, _
ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Dim Ret As Long

Sub Sample()
    Dim ws As Worksheet
    Dim LastRow As Long, i As Long
    Dim strPath As String

    '~~> Name of the sheet which has the list
    Set ws = Sheets("Sheet1")

    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

    For i = 1 To LastRow '<~~ 2 because row 1 has headers
        Ret = URLDownloadToFile(0, ws.Range("A" & i).Value, ws.Range("B" & i).Value, 0, 0)
'URLDownloadToFile(0, ,
        If Ret = 0 Then
            ws.Range("D" & i).Value = "File successfully downloaded"
        Else
            ws.Range("D" & i).Value = "Unable to download the file"
        End If
    Next i
End Sub

Friday, October 7, 2016

Create User Define Function and Macro as an Add-in


We work lot in excel and manage our work with functions and macros. I am here creating the process that will save your time and effort to re-create again and again the same functions or macros.

Here we are going to create Add-in that will automatically load when you open your excel, and the function will be available all the time. So let's start.

Step 1: Quickly create an empty add-in for excel


  1. Open excel and Save a blank workbook as a Excel Add-In (*.xlam) in your Add-In folder (%UserProfile%\AppData\Roaming\Microsoft\AddIns)
  2. I named it PersonalAddIn.xlam (Save it with any name you like)
  3. Click Office button.
  4. Click "Excel options" button.
  5. Click "Add-Ins" tab.
  6. Select "Excel Add-ins" from manage dropdown list and click GO
  7. Click "Browse" button
  8. Select the (.xlam) file that you just saved in step 1
  9. Click OK (Make sure you enable)



Step 2: Add custom functions and macros to your personal add-in

  1. Go to the Developer Tab on the ribbon.
  2. Click "View Code"
  3. Click on the project panel you see VBAProject (*.xlam)
  4. Click Insert Menu --> Module
  5. Copy and paste custom functions and macros to code window.


That's it... we are done.

Step 3: Use your user define function

  1. Go to the cell
  2. Click "Insert Function" in formula bar
  3. Select category "User Defined"
  4. Select your custom function
  5. Click OK


Step 4: Use your user define Macro

  1. Go to "Developer" tab
  2. Click "Macros" button
  3. Select/Type the macro name
  4. Click "Run"


Hope this will help you in you daily work, In case of any query you can write to me. Thanks for reading.

Thursday, April 28, 2016

Get FileName list form a Folder in EXCEL

The code below retrieves the file in this directory and creates a list of their names and paths:

Sub GetFileNameList()

Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim i As Integer

'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")

'Get the folder object
Set objFolder = objFSO.GetFolder("C:\TMP")

i = 1
'loops through each file in the directory and prints their names and path

For Each objFile In objFolder.Files

    'print file name
    Cells(i + 1, 1) = objFile.Name

    'print file path
    Cells(i + 1, 2) = objFile.path
    i = i + 1

Next objFile

End Sub

Monday, June 16, 2014

How To Get Last Row in Excel VBA code

There are many programmatic way to find last row of data input, but the simplest is....

Dim LastRow 
LastRow = ws.Range("A1").End(xlDown).Row


Wednesday, July 17, 2013

Extracting text from a bunch of =EMBED(“Forms.HTML:Text.1”,“”) in Excel

Sub ExtractData()
Dim obj

    For Each obj In ActiveSheet.OLEObjects
        If obj.progID = "Forms.HTML:TextArea.1" Then
            me.Range("A1").Value = obj.Object.Value 
             ''' change the Range as required
        End If
    Next o
End Sub

Wednesday, December 28, 2011

Spell you Number in Words






Function SpellNumber(ByVal n As Double, _
                     Optional ByVal useword As Boolean = True, _
                     Optional ByVal ccy As String = "Dollars", _
                     Optional ByVal cents As String = "", _
                     Optional ByVal join As String = " And", _
                     Optional ByVal fraction As Boolean = False) As String
Dim myLength As Long
Dim i As Long
Dim myNum As Long
Dim Remainder As Long


    SpellNumber = ""
    Remainder = Round(100 * (n - Int(n)), 0)


    myLength = Int(Application.Log10(n) / 3)


    For i = myLength To 0 Step -1
        myNum = Int(n / 10 ^ (i * 3))
        n = n - myNum * 10 ^ (i * 3)
        If myNum > 0 Then
            SpellNumber = SpellNumber & MakeWord(Int(myNum)) & _
            Choose(i + 1, "", " thousand ", " million ", " billion ", " trillion")
        End If
    Next i
    SpellNumber = SpellNumber & IIf(useword, " " & ccy, "") & _
                    IIf(Remainder > 0, join & " " & Format(Remainder, "00"), " Only") & _
                    IIf(fraction, "/100", "") & " " & cents
    SpellNumber = Application.Proper(Trim(SpellNumber))


End Function




Function MakeWord(ByVal inValue As Long) As String
Dim unitWord, tenWord
Dim n As Long
Dim unit As Long, ten As Long, hund As Long


    unitWord = Array("", "one", "two", "three", "four", _
                     "five", "six", "seven", "eight", _
                     "nine", "ten", "eleven", "twelve", _
                     "thirteen", "fourteen", "fifteen", _
                     "sixteen", "seventeen", "eighteen", "nineteen")
    tenWord = Array("", "ten", "twenty", "thirty", "forty", _
                    "fifty", "sixty", "seventy", "eighty", "ninety")
    MakeWord = ""
    n = inValue
    If n = 0 Then MakeWord = "zero"
    hund = n \ 100
    If hund > 0 Then MakeWord = MakeWord & MakeWord(Int(hund)) & " hundred "
    n = n - hund * 100
    If n < 20 Then
        ten = n
        MakeWord = MakeWord & unitWord(ten) & " "
    Else
        ten = n \ 10
        MakeWord = MakeWord & tenWord(ten) & " "
        unit = n - ten * 10
        MakeWord = Trim(MakeWord & unitWord(unit))
    End If
    MakeWord = Application.Proper(Trim(MakeWord))


End Function

Friday, March 4, 2011

Replace text into your .txt file with VBA

FielPath : Location of your Text file including file name. e.g.: c:\abc\abc.txt
oldStr : search string into the file 
newStr: replace the value with oldStr.


Sub TestReplaceTextInFile(filePath As String, oldStr As String, newStr As String)
    ReplaceTextInFile filePath, oldStr, newStr
End Sub

Sub ReplaceTextInFile(SourceFile As String, sText As String, rText As String)
    Dim TargetFile As String, tLine As String, tString As String
    Dim p As Integer, i As Long, F1 As Integer, F2 As Integer
        TargetFile = "RESULT.TMP"
        If Dir(SourceFile) = "" Then Exit Sub
        If Dir(TargetFile) <> "" Then
            On Error Resume Next
            Kill TargetFile
            On Error GoTo 0
            If Dir(TargetFile) <> "" Then
                MsgBox TargetFile & _
                    " already open, close and delete / rename the file and try again.", _
                    vbCritical
                Exit Sub
            End If
        End If
        F1 = FreeFile
        Open SourceFile For Input As F1
        F2 = FreeFile
        Open TargetFile For Output As F2
        i = 1 ' line counter
        Application.StatusBar = "Reading data from " & _
            TargetFile & " ..."
        While Not EOF(F1)
            If i Mod 100 = 0 Then Application.StatusBar = _
                "Reading line #" & i & " in " & _
                TargetFile & " ..."
            Line Input #F1, tLine
            If sText <> "" Then
                ReplaceTextInString tLine, sText, rText
            End If
            Print #F2, tLine
            i = i + 1
        Wend
        Application.StatusBar = "Closing files ..."
        Close F1
        Close F2
        Kill SourceFile ' delete original file
        Name TargetFile As SourceFile ' rename temporary file
        Application.StatusBar = False
End Sub


Private Sub ReplaceTextInString(SourceString As String, _
        SearchString As String, ReplaceString As String)
    Dim p As Integer, NewString As String
        Do
            p = InStr(p + 1, UCase(SourceString), UCase(SearchString))
            If p > 0 Then ' replace SearchString with ReplaceString
                NewString = ""
                If p > 1 Then NewString = Mid(SourceString, 1, p - 1)
                NewString = NewString + ReplaceString
                NewString = NewString + Mid(SourceString, _
                    p + Len(SearchString), Len(SourceString))
                p = p + Len(ReplaceString) - 1
                SourceString = NewString
            End If
            If p >= Len(NewString) Then p = 0
        Loop Until p = 0
End Sub

Tuesday, August 17, 2010

Convert a numeric value to English words





Convert a numeric value to English words:

I have found many location where people who use excel they want to change the numeric value to words. Following code can help you for the same !!!





                                                                                                                                    

Option Explicit
Public Numbers As Variant, Tens As Variant


Sub updateArrayNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub


Function WordToNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String


If Abs(MyNumber) > 999999999 Then
WordToNum = "Value too large"
Exit Function
End If


updateArrayNums


NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))


For n = 3 To 1 Step -1
StrNo = Format(ValNo(n), "000")


If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If


If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordToNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordToNum = Trim(Temp2 & Temp1 & " thousand " & WordToNum)
If n = 1 Then WordToNum = Trim(Temp2 & Temp1 & " million " & WordToNum)


End If
Next n


NumStr = Trim(Str(Abs(MyNumber)))


' check after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordToNum = WordToNum & Temp1
End If


If Len(WordToNum) = 0 Or Left(WordToNum, 2) = " p" Then
WordToNum = "Zero" & WordToNum
End If
End Function


Function GetTens(TensNum As Integer) As String
' Converts a num to txt from 0 to 99.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function


                                                                                                                                    


enjoy VBA coding...

Monday, June 28, 2010

UDF (User Defile Function) in EXCEL

About User Defined Functions

Excel provides the user with a large collection of functions inbuilt, more than enough to satisfy the average user. Many more functions can be added by installing the various add-ins that are available on internet.

Most of the calculations can be easily done with the inbuilt functions provided by Microsoft,  but it isn't long before you find yourself wishing that there was a function that did a particular job, and you can't find anything suitable in the list. You need a UDF.

A UDF (User Defined Function) is simply a function that you create yourself with VBA. UDFs are often called "Custom Functions". A UDF can remain in a code module attached to a workbook, in which case it will always be available when that workbook is open. Alternatively you can create your own add-in containing one or more functions that you can install into Excel just like a commercial add-in.

UDFs can be accessed by code modules too. Often UDFs are created by developers to work solely within the code of a VBA procedure and the user is never aware of their existence.

Like any function, the UDF can be as simple or as complex as you want. Let's start with an easy one...

A function that will calculate Simple interest.

Open a new workbook and then open the Visual Basic Editor (Tools > Macro > Visual Basic Editor or ALT+F11).

You will need a module in which to write your function so choose Insert > Module. Into the empty module type: Function SimpleInterest and press ENTER.
The Visual Basic Editor completes the line for you and adds an End Function line as if you were creating a subroutine.
You will find it as follow:

Function SimpleInterest()

End Function
 For calculation of simple interest we need 3 values from user i.e. Principal Amount, Rate of Interest, and Number of period. So, we will add 3 parameter to the function, and calculation of the Simple Interest.

 
Function SimpleInterest(pAmt As Double, rate As Integer, period as Integer)
 Dim si as Double
 si = (pAMT * rate * period)/ 100                  ' (PRN/100)
 SimpleInterest = si                               ' return value 
End Function

Now we can test our function right away. Switch to the Excel window and enter figures for principal, rate of interest and period in separate cells. In a fourth cell enter your function as if it were one of the built-in ones. In this example cell A2 contains the Principal Amount (1000), cell B2 has Rate of Interest (12%) and cell C2 has period(24). In D2 I typed =SimpleInterest(A2,B2,C2) and the new function calculated the simple interest  (28.8)...









A function that will give Name of Weekday

There is a function in Excel that return me the number of Week, but I want name of the week not a number!!! So, let's create function that will show us name of week(like "Monday").
We can do this by doing manipulation the inbuilt function. But I don't it to do every time so I decided to create a Custom user define function, that will full fill my requirement.


So, Let's Start...

Function WeekDayName(InputDate As Date)
    Dim wDay As Integer    Dim wDayName As String
 
    wDay = Weekday(InputDate, vbSunday)         ' vbSunday is set as defaule start date
    Select Case wDay
        Case 1
            WeekDayName = "Sunday"
        Case 2
            WeekDayName = "Monday"
        Case 3
            WeekDayName = "Tuesday"
        Case 4
            WeekDayName = "Wednesday"
        Case 5
            WeekDayName = "Thursday"
        Case 6
            WeekDayName = "Friday"
        Case 7
            WeekDayName = "Saturday"
    End Select
End Function

I've called my function "WeekDayName" and it takes a single argument, which I call "InputDate" which (of course) has to be a date. Here's how it works...
  • The first line of the function declares a variable that I have called "WeekDayNumber" which will be an Integer (i.e. a whole number).
  • The next line of the function assigns a value to that variable using Excel's WEEKDAY function. The value will be a number between 1 and 7. Although the default is 1=Sunday, I've included it anyway for clarity.
  • Finally a Case Statement examines the value of the variable and returns the appropriate piece of text. 








Were do we find our custom function in Excel?
You can also find the functions listed in the Function Wizard (sometimes called the Paste Function tool). Use the wizard to insert a function in the normal way (Insert > Function).
Scroll down the list of function categories to find User Defined and select it to see a list of available UDFs...


Extract Flash Game from Excel with VBA

Open new Excel file and insert new ActiveX Button control past following code in it's Click function.

Private Sub CommandButton1_Click()
    Dim tmpFileName As String, FileNumber As Integer 
    Dim myFileId As Long 
    Dim myArr() As Byte 
    Dim i As Long 
    Dim MyFileLen As Long, myIndex As Long 
    Dim swfFileLen As Long 
    Dim swfArr() As Byte 
    tmpFileName = Application.GetOpenFilename("office File(*.doc;*.xls),*.doc;*.xls", , "Select Excel / Word File") 
    If tmpFileName = "False" Then Exit Sub 
    myFileId = FreeFile 
    Open tmpFileName For Binary As #myFileId 
    MyFileLen = LOF(myFileId) 
    ReDim myArr(MyFileLen - 1) 
    Get myFileId, , myArr() 
    Close myFileId 
    Application.ScreenUpdating = False 
    i = 0 
    Do While i < MyFileLen 
        If myArr(i) = &H46 Then 
            If myArr(i + 1) = &H57 And myArr(i + 2) = &H53 Then 
                swfFileLen = CLng(&H1000000) * myArr(i + 7) + CLng(&H10000) * myArr(i + 6) + _ 
                CLng(&H100) * myArr(i + 5) + myArr(i + 4) 
                ReDim swfArr(swfFileLen - 1) 
                For myIndex = 0 To swfFileLen - 1 
                    swfArr(myIndex) = myArr(i + myIndex) 
                Next myIndex 
                Exit Do 
            Else 
                i = i + 3 
            End If 
        Else 
            i = i + 1 
        End If 
    Loop 
    myFileId = FreeFile 
    tmpFileName = Left(tmpFileName, Len(tmpFileName) - 4) & ".swf" 
    Open tmpFileName For Binary As #myFileId 
    Put #myFileId, , swfArr 
    Close myFileId 
    MsgBox "SaveAs " & tmpFileName 
End Sub