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

Tuesday, September 6, 2016

How to Install the Macro

Now a days excel automation is in trend. For automation we have to write VBA code, sometimes we need not to write codes; we can find them on Internet by simply searching our requirement. Once we get the code we just need to install that code in our desired file. You can install the code by simply following the beneath steps:


  1. Select and Copy the entire code
  2. Open the Microsoft Excel file in which you would like the Macro to function
  3. Press "Alt + F11" - This will open the Visual Basic Editor - Works for all Excel Versions. Or For other ways look at beneath steps:
    1. For Excel Versions Prior to Excel 2007
      Go to Tools > Macros > Visual Basic Editor
    2. For Excel 2007
      Go to Office Button > Excel Options > Popular > Click Show Developer tab in the Ribbon. Then go to the Developer tab on the ribbon menu and on the far left Click Visual Basic
  4. On the new window that opens up, go to the left side where the vertical pane is located. Locate your Excel file; it will be called VBAProject (YOUR FILE'S NAME HERE) and click this.


  5. If the Macro goes in a Module, look at beneath steps, otherwise continue to Step 8.
    1. Go to the menu at the top of the window and click Insert > Module
    2. Another window should have opened within the Visual Basic Editor's window. Within this new window, paste the macro code. Make sure to paste the code underneath the last line of anything else that is in the window.
    3. Go to Step 8.
  6. If the Macro goes in the Workbook or ThisWorkbook, look at beneath steps, otherwise continue to Step 8.
    1. Directly underneath your excel file called VBAProject(your file's name here), click the Microsoft Excel Objects folder icon to open that drop-down list.
    2. Then, at the bottom of the list that appears, double-click the ThisWorkbook text.
    3. A new window inside the Visual Basic Editor's window will appear. In this new window, paste the code for the macro. Make sure to paste this code underneath the last line of any other code which is already in the window.
    4. Go to Step 8.
  7. If the Macro goes in the Worksheet Code, look at beneath steps, otherwise continue to Step 8.
    1. Directly underneath your excel file called VBAProject(your file's name here), click the Microsoft Excel Objects folder icon to open that drop-down list.
    2. Within the list that appears you will see every worksheet that is in that excel file. They will be listed as such: Sheet1(NAME OF SHEET HERE) and under that will be Sheet2(NAME OF SHEET HERE). Select the sheet in which you want the macro to run and double-click that sheet.
    3. A new window inside the Visual Basic Editor's window will appear. In this new window, paste the code for the macro. Make sure to paste this code underneath the last line of any other code which is already in the window.
    4. Repeat steps b and c for every sheet you want the macro to work in. Putting the macro in one sheet will not enable it for any other sheets in the workbook.
    5. Go to Step 8.


  8. Close the Microsoft Visual Basic Editor window and save the Excel file. When you close the Visual Basic Editor window, the regular Excel window will not close.
  9. You are now ready to run the macro.

Monday, June 27, 2016

VBA Code to clear Content in Entire Sheet

VBA Code to clear an entire sheet in Excel uses the clear contents method, however all that does is clear the data from the cells and not the formatting. To truly clear all the cells and start with a blank canvas you need to use the delete method. Finally we looked at the structure of the VBA script and how to amend it to change your VBA from deleting the contents of cells to deleting the entire worksheet from your Excel workbook.

VBA Code Syntex 

 Sheets(“INSERT WORKSHEET NAME HERE”).Cells.ClearContents  

VBA Code/Macro to Clear Content

 Sub ClearSheet()  
 Sheets(“Sheet1”).Cells.ClearContents  
 End Sub  
OR
 Sub ClearSheet()  
 Sheets(“Sheet1”).Cells.Delete  
 End Sub  
OR
 Sub ClearSheet()  
 Sheets(“Sheet1”).Delete  
 End Sub  

Friday, April 15, 2016

Show a Processing Window While Macro Runs

Step-by-step process to show a processing window While Macro Runs in excel:



Processing GIF Image

  1. Start a new workbook in Microsoft Excel 97, 2003, 2007, 2010, 2013, 2016. (or a new document in Microsoft Word 97, 2003, 2007, 2010, 2013, 2016, 2019, Office365).
  2. Press ALT+ F11 to activate the Visual Basic Editor.
  3. On the Insert menu, click Module to insert a module into the project.
  4. Press F4 to display the Properties window.
  5. Change the Name property of the module to Processing_Code.
  6. In the Processing_Code module window, type or copy-paste the following code:
  7. Public Processing_Message As String
    Public Macro_to_Process As String
    
    Sub StartProcessing (msg As String, code As String)
         Processing_Message = msg    'Set the message that is displayed
                                     'in the dialog box
         Macro_to_Process = code     'Set the macro that is run after the
                                     'dialog box is active
         Processing_Dialog.Show      'Show the Dialog box
    End Sub
    

  8. On the Insert menu, click UserForm to add a UserForm to the project.
  9. Press F4 to display the Properties Window. Change the UserForm properties to the following settings.




  10. Property           Setting
    -------------------------------------
    Name               Processing_Dialog
    Caption            Please Wait...
    StartUpPosition    2-CenterScreen
    
  11. Add one Label control to the UserForm. Change the Name property of the label to lblMessage.
  12. Select the UserForm. On the View menu, click Code. In the code window, in the Procedure list, select the Initialize event, and then type the following in the Code window:
  13. Private Sub UserForm_Initialize()
        lblMessage.Caption = Processing_Message  'Change the Label Caption
    End Sub
    
  14. In the Code window, click Activate event in the Procedure list, and type the following:
  15. Private Sub UserForm_Activate()
          Me.Repaint                         'Refresh the UserForm
          Application.Run Macro_to_Process   'Run the macro
          Unload Me                          'Unload the UserForm
    End Sub
    

  16. On the Insert menu, click Module. Type the following code in the Code window:




  17. Sub MyMacro()
          For x = 1 to 5000
              Application.StatusBar = x   '5000 Iterations Changing StatusBar
          Next
          Application.StatusBar = False  'Reset the StatusBar
    End Sub 
     Sub Main()
          'Call the StartProcessing procedure to show the Processing_Dialog
          'with the label "Processing, Please Wait..." and execute
          'MyMacro.
          StartProcessing "Processing, Please Wait...", "MyMacro"
    End Sub
    
  18. Press ALT+ Q to leave the Visual Basic Editor and return to Microsoft Excel (or Microsoft Word).
  19. On the Tools menu, point to Macro, and click Macros. Select the Main macro and click Run. The Processing_Dialog dialog box appears.
While the dialog box is shown, the status bar text in the application increments from 1 to 5000--the changing status bar text is the indication that your macro is running while the dialog box is on the screen.





How to Use the Processing Dialog Box in Other Workbooks


To use this "Processing, Please Wait" dialog box with macros in other workbooks or documents, do the following:
  1. Activate the Visual Basic Editor. On the View menu, click Project Explorer.
  2. Select the project that you created in the previous steps.
  3. Right-click the "Processing_Dialog" UserForm and click Export File. Save the UserForm as "Processing_Dialog.frm."
  4. Right-click the "Processing_Code" Module and click Export File. Save the module as "Processing_Code.bas."
  5. Return to Microsoft Excel and open the workbook in which you would like to use the "Processing, Please Wait" dialog box.
  6. Activate the Visual Basic Editor.
  7. On the File menu, click Import File, select the "Processing_Dialog.frm" file, and click Open.
  8. On the File menu, click Import File. Select the "Processing_Dialog.bas" file, and click Open.
  9. On the Insert menu, click Module, and type the following code in the Code window:
  10. Sub Main()
             StartProcessing "<message text>", "<macro name>"
    End Sub
    
    Where the <message text> argument is the text string that you want to display in the Processing_Dialog dialog box and <macro name> is the macro that you would like to run after the dialog box appears. To show the dialog box and run the macro indicated by "<macro name>", run the macro Main.



Monday, January 18, 2016

Transpose the Bulk address data using the Macro or VBA code

Transpose the Bulk address data using the Macro or VBA code:

Query is mentioned in the below image:

Solution:

Sub TransposeColToRow()
Dim LastRow As Integer
Dim j As Integer
Dim SaveJ As Integer
Dim Myvalue As String
Dim CurrValue
LastRow = Range(“A65536”).End(xlUp).Row
k = 0
l = 0
For j = 1 To LastRow
If Range(“A” & j).Value “” Then
Range(“D1”).Offset(k, l).Value = Range(“A” & j).Value
l = l + 1
Else
l = 0
k = k + 1
End If
Next j
End Sub

Thursday, February 19, 2015

Separate Strings through VBA Code

In this tutorial we are going to explain you how you can separate the strings using the VBA Macro Code in Microsoft Excel.

Below Is the Situation in which you need to separate the Full Name string to the First Name and the Last Name string:

Separate Strings Excel Query Image

You can place a command button on your worksheet (as shown in the above screenshot) And add the following code lines: 

  1. We Declare a variable called Full_Name of Type String, a variable called Comma_Position of Type Integer, And a variable called i of Type Integer.
  2.     Dim Full_Name As String, Comma_Position As Integer, i As Integer
    

    The problem we are dealing With Is that we need To tell Excel VBA from where we want To separate the string. In Case of Smith, Mike the comma is at position 6 While in Case of Williams, Janet the comma is at position 9. 




  3. We use a loop to execute the operations on each name entered in Excel. First, we initialize the variable Full_Name. Next, we use the Instr function to find the position of the comma.
  4.     For i = 2 To 7
        Full_Name = Cells(i, 1).Value
        Comma_Position = InStr(Full_Name, ",")
    
    Note: Currently this code is working from Row No. 2 to 7. You can modify it as per your requirement.

  5. Now, we want to write the part after the comma to Column B and the part in front of the comma to column C. You can achieve this by adding below mentioned lines in you code:
  6. Cells(i, 2).Value = Mid(Full_Name, Comma_Position + 2)
    Cells(i, 3).Value = Left(Full_Name, Comma_Position - 1)
    
    Mid(Full_Name, Comma_Position + 2) means we want the part of Full Name starting at character 'Comma_Position + 2' (this is exactly the first name).

    Left(Full_Name, Comma_Position - 1) means we want the part of Full Name starting at the beginning until character 'Comma_Position - 1' (this is exactly the last name).

  7. Now, close the loop.
  8.     Next i
    


  9. Final Code will look like below:
  10. Sub Separate_Strings()
    
        Dim Full_Name As String, Comma_Position As Integer, i As Integer
    
        For i = 2 To 7 'You can modify it as per your requirement.
            Full_Name = Cells(i, 1).Value
            Comma_Position = InStr(Full_Name, ",")
        
        Cells(i, 2).Value = Mid(Full_Name, Comma_Position + 2)
        Cells(i, 3).Value = Left(Full_Name, Comma_Position - 1)
        
        Next i
    
    End Sub
    
  11. To test the program, Add six names separated by a comma and space to Range("A2:A7") as shown in the above screenshot.
  12. Test the program.

Result:

Separate Strings Excel Result Image 



InputBox function in Excel VBA Code

InputBox Function

You can use the InputBox function in Excel VBA to prompt the user to enter a value. Place a command button on your worksheet and add the following code lines:

1. First, declare the variable myValue of type Variant.
Dim myValue As Variant

Note: we use a variable of type Variant here because a Variant variable can hold any type of value. This way the user can enter text, numbers, etc.

2. Add the following code line to show the input box.
myValue = InputBox("Give me some input")

InputBox Function in Excel VBA

3. Write the value of myValue to cell A1.
Range("A1").Value = myValue

Result when the user enters the value 5 and clicks the OK button.

InputBox Function Result

4. The InputBox function has more optional arguments. The following code line shows an input box with a title displayed in the title bar and has a default value. The default value will be used if no other input is provided.
myValue = InputBox("Give me some input", "Hi", 1)

InputBox Function in Excel VBA 







Result when the user only clicks the OK button.

InputBox Function Result

Note: Place your cursor on InputBox in the Visual Basic Editor and click F1 for help on the other optional arguments.

VBA Code for excel to send multiple emails using Outlook

In this tutorial we will explain you, how you can send the multiple e-mails from Microsoft Excel using Outlook. The best part of this code is, each recipient will receive the email individually. Before proceeding further there are some prerequisite:

You need to make the excel sheet format as defined below:

  1. Place the list of e-mail addresses under column "A"
  2. Place the e-mail subject line in cell "B1"
  3. Place the e-mail body message in cell "B2" and then,
  4. Use the following VBA code to send the email to each individual email address using MS outlook.

Note: This code will send the e-mail to each e-mail address listed in the Column "A" starting at row 2 down to the last row.

At the moment this code is set to display before sending. If you don't want to see or review each e-mail before sending then, you can disable or comment the display line and enable or un-comment the Send line.

Code:

Dim i As Integer, Mail_Object, Email_Subject, o As Variant, lr As Long
lr = Cells(Rows.Count, "A").End(xlUp).Row
Set Mail_Object = CreateObject("Outlook.Application")
For i = 2 To lr
       With Mail_Object.CreateItem(o)
           .Subject = Range("B1").Value
           .To = Range("A" & i).Value
           .Body = Range("B2").Value
           '.Send
           .display 'disable display and enable send to send automatically
    End With
Next i
       MsgBox "E-mail successfully sent", 64
       Application.DisplayAlerts = False
Set Mail_Object = Nothing
End Sub


VBA Code to show MsgBox in MS Excel

In this tutorial we are going to explain you how you show the MsgBox in Microsoft Excel using the VBA Code. The MsgBox is a dialog box in Excel VBA, you can use To inform the users of your program. Place a command button On your worksheet and add the following code lines: 

  1. Code To show a simple message in the MsgBox:
  2.     MsgBox "This Is fun"
    

    Result when you click the command button On the sheet: 

    msg box image

  3. Code To show a little more advanced message. First, enter a number into cell A1 And Then run the below code:
  4.     MsgBox "Entered value Is " & Range("A1").Value
    
    Result when you click the command button On the sheet:



    msg box with value image


    Note: we used the & operator To concatenate (join) two strings. Although Range("A1").value Is Not a string, it works here.

  5. To start a new line in a message, use vbNewLine.
  6.     MsgBox "Line 1" & vbNewLine & "Line 2"
    
    Result when you click the command button On the sheet:
msg box in multiple lines image


Sunday, February 8, 2015

VBA Code to Remove Specific Value from a table in MS Excel

Use the Below VBA Code to Remove Specific Value from a table in MS Excel from your active worksheet


 Sub RemoveSpecificValue()  
 'Removing Specific Values whose begins with "FR0"  
    ActiveSheet.Range("A:G").AutoFilter Field:=1, Criteria1:="=FR0*" _  
     , Operator:=xlAnd  
   ' Delete AutoFiltered rows except the header  
   lr = Cells(Rows.Count, 1).End(xlUp).Row  
   If lr > 1 Then  
     Range("A2:A" & lr).SpecialCells(xlCellTypeVisible).EntireRow.Delete  
   End If  
 End Sub  


VBA Code to Delete Multiple Rows in MS Excel

Use Below VBA Code to Delete Multiple Rows in MS Excel from your active worksheet

Sub DeleteRows()
'Delete the Row 2 and 4 in active worksheet
    Rows("2:2,4:4").Select
    Selection.Delete Shift:=xlUp
End Sub

VBA Code to Delete Multiple Columns in MS Excel

Use Below VBA Code to Delete Multiple Columns in MS Excel from your active worksheet
Sub DeleteColumns()

'Delete the Column B and D in the active worksheet

    Columns("B:B, D:D").Select 

    Selection.Delete Shift:=xlToLeft

End Sub


VBA Code to autofit columns in MS Excel

Use Below VBA Code to autofit the columns in MS Excel as per you requirement

Sub AutoFitColumns()
     Dim sht As Worksheet

'AutoFit all the Columns in active worksheet
    Cells.Select
    Cells.EntireColumn.AutoFit

'AutoFit One Column
    ThisWorkbook.Worksheets("Sheet1").Columns("O:O").EntireColumn.AutoFit
  
'AutoFit Multiple Columns
    ThisWorkbook.Worksheets("Sheet1").Range("I:I,L:L").EntireColumn.AutoFit 'Columns I & L
    ThisWorkbook.Worksheets("Sheet1").Range("I:L").EntireColumn.AutoFit 'Columns I to L
  
'AutoFit All Columns on Worksheet
    ThisWorkbook.Worksheets("Sheet1").Cells.EntireColumn.AutoFit

'AutoFit Every Worksheet Column in a Workbook
    For Each sht In ThisWorkbook.Worksheets
        sht.Cells.EntireColumn.AutoFit
    Next sht


End Sub