Total Pageviews

Showing posts with label excel vba. Show all posts
Showing posts with label excel vba. Show all posts

Thursday, October 25, 2018

How to Select a Named Range on the Active Worksheet



















To select the named range "StudentDetails" on the active worksheet, you can use either of the following examples:

Range("StudentDetails").Select

Application.Goto "StudentDetails"

How to Select a Range of Cells on a Worksheet in a Different Workbook




















To select the range E5:J10 on a worksheet (Sheet5) in a different workbook (Book5.xlsx), you can use either of the following examples:

Application.Goto Workbooks("BOOK5.xlsx").Sheets("Sheet5").Range("E5:J10")

Application.Goto Workbooks("BOOK5.xlsx").Sheets("Sheet5").Range("E5", "J10")

Or, you can activate the worksheet, and then use method 4 above to select the range:

Workbooks("BOOK5.xlsx").Sheets("Sheet5").Activate
ActiveSheet.Range(Cells(5, 5), Cells(10, 10)).Select

How to Select a Range of Cells on Another Worksheet in the Same Workbook



















To select the range E5:J10 on another worksheet (Sheet5) in the same workbook, you can use either of the following examples:

Application.Goto ActiveWorkbook.Sheets("Sheet5").Range("E5:J10")
Application.Goto ActiveWorkbook.Sheets("Sheet5").Range("E5", "J10")

Or, you can activate the worksheet, and then use method 4 above to select the range:

Sheets("Sheet5").Activate
ActiveSheet.Range(Cells(5, 5), Cells(10, 10)).Select

How to Select a Cell on Another Worksheet in the Same Workbook














To select cell F7 on another worksheet (Sheet3) in the same workbook, you can use either of the following examples:

Application.Goto ActiveWorkbook.Sheets("Sheet3").Cells(7, 6)

   -or-
 
Application.Goto (ActiveWorkbook.Sheets("Sheet3").Range("F7"))

You can also activate the worksheet, and then use method 1 above to select the cell:
Sheets("Sheet3").Activate
ActiveSheet.Cells(7, 6).Select

How to Select a Cell on a Worksheet in a Different Workbook















To select cell D4 on a worksheet (Sheet2) in a different workbook (Book2.xlsx), you can use either of the following examples:

Application.Goto Workbooks("Book2.xlsx").Sheets("Sheet2").Cells(4, 4)

    -or-

Application.Goto Workbooks("Book2.xlsx").Sheets("Sheet2").Range("D4")

You can also activate the worksheet, and then use method 1 above to select the cell:
Workbooks("Book2.xlsx").Sheets("Sheet2").Activate
ActiveSheet.Cells(4, 4).Select

How to Select a Range of Cells on the Active Worksheet
















To select the range B2:D4 on the active worksheet, you can use any of the following examples:

ActiveSheet.Range(Cells(2, 2), Cells(4, 4)).Select

ActiveSheet.Range("B2:D4").Select

ActiveSheet.Range("B2", "D4").Select

How to Select a Cell on the Active Worksheet
















To select cell C4 on the active worksheet, you can use either of the following examples:

ActiveSheet.Cells(4, 3).Select

-or-

ActiveSheet.Range("C4").Select

Sunday, March 11, 2018

Automatic Birthday Mailer


This blog will help you send automatic mailer’s for birthdays, work anniversaries, marriage anniversaries, etc. Assuming almost everyone has Microsoft office in your systems, it is built on Microsoft Excel VBA platform.

These are the following options available on the tool:
1. It can send random customized messages for everyone on the list.
2. Attach a birthday Picture for everyone.
3. Set any Gmail/Yahoo/Office email id to send the mails.
4. Keep a bcc mail id to track if things are working fine.
5. Save the status of the last execution instance.

There is a batch file which opens the MS Excel file. Use the windows task scheduler for triggering the batch file on a particular time daily. Best is to keep the files on a server that is running all the time. And schedule the task on the server. Fill the details in the excel files as per your requirement.
Select pictures that you want to send as attachment.

Keep all the pictures in the Attachment folder, give all the file names a sequential ordering. It will be easier to identify in the excel file. Select images for similar type, i.e. same file extension, it’s easier to update later.

Select at least 20% unique messages. Add them to the MESSAGE sheet. Make sure to update the serial number in the MESSAGE sheet. Similar thing can be dome for customizing the subject lines.

Update the formula for the attachment and body according to your requirement.
The syntax would be:
=RANDBETWEEN(1,<number of unique attachments>)&".<FileExtension>"
=INDEX(Message!$B$2:$B$<row number of last item>,RANDBETWEEN(1,<number of unique messages>))

CODE MODIFICATION:
Open the Visual Basic Editor > Go to ThisWorkbook code section.
1. To send the mail from your laptop/Server configured outlook
    Call Module1.automated_email
2. To send the mail from gmail ID
    Call Module2.automated_email_gmail
3. To commit your execution instance
    ActiveWorkbook.Save
4. To close the workbook after execution
    ActiveWorkbook.Close

In the module2 update this two lines with your specific detail
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "SenderEmail@gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "SenderEmailPassword"

Here the SenderEmail ID has to be a Gmail ID because the configuration in module 2 is set as per Gmail’s SMTP configuration,

If you want to send mail from Yahoo Mail the go to this link to get the SMTP configuration
http://warlocksolutions.blogspot.in/2017/08/automated-emails-from-excel-via-YahooMail.html

If you have your own Mail Server then best way is to use the Outlook method for sending. OR you can ask the server configuration details from your mail admin and update the same in the code.

IMPORTANT THING TO REMEMBER, FOLLOW STEP WISE:
1. The Attachments folder should be in the same directory where the BirthdayMailer file is placed.
2. After you update the file with new birthday details SAVEAS the file with current date.
3. In the code inside ThisWorkbook, Uncomment 1 OR 2 (Outlook or Gmail) as per your need. Also uncomment 3 AND 4 (Save and Close).
4. SAVEAS the file without current Date (BirthdayMailer.xlsm), after you close this file you cannot open this file anymore because the file will open, execute the code, save and then auto close. Replace the file in the laptop/server with this file.
5. In order to update new details next time, use the file with the date in the filename and repeat from step 1

HOW TO SET UP THE TRIGGER:
1. Right click on the batch file (trigger.bat) > Edit, Update the code and save it:
START EXCEL.EXE "<YOUR DESIRED LOCATION>\BirthdayMailer.xlsm"
2. Go to windows Task Scheduler and create a Basic Task:
3. Give a name to the Task. Ex: Birthday
4. Trigger Daily, Set the time as per your requirement.
5. Action > Start a program
6. Program/script: Browse the trigger.bat file
7. Select “Open the properties dialog for this task…” before you click finish.
8. In the properties window, update the run settings as per your requirement and save.
I would suggest keep all the files in one folder in the server.
1. BirthdayMailer.xlsm
2. trigger.bat
3. Attachments Folder

For any other queries please use the comments section below.

Please put your thoughts and comments below so that I can improve.

THANKS EVERYONE.

SUBHAJIT.


Wednesday, March 7, 2018

Selection of a specific sheet from a workbook

Hello Everyone,

The use case is as follows:
Data file which contains separate sheets for separate data. You need to select one sheet from all the available sheets in the file. 

In this example, 
1. User is asked to browse the data file
2. An userform shows a list of all the available sheets in the file
3. You select the required sheet and the data will be copied to your Tool workbook.

This may not be useful alone but you can combine this to your existing automation's where you are required to copy paste a data from a specific sheet in a file.

CODE in the module
===============
Sub fileOpen()
    toolWorkbook = ActiveWorkbook.Name
    On Error Resume Next
    data.Select
    data.Cells.Clear
    data.Range("A1").Select
    Dim strFileToOpen As String
    strFileToOpen = Application.GetOpenFilename(Title:="Please select an Excel file to open", FileFilter:="Excel Files *.xls* (*.xls*),")
    If strFileToOpen = "False" Then
        MsgBox "No file selected.", vbExclamation, "Status"
        Exit Sub
    Else
        Workbooks.Open Filename:=strFileToOpen
    End If
    dataWorkbook = ActiveWorkbook.Name
    frm_sheetSelect.Show
End Sub

Sub copyData()
    Dim tempName As String
    Workbooks(dataWorkbook).Activate
    ActiveSheet.Select
    
    tempName = ActiveSheet.Name
    
    Cells.Select
    Selection.Copy
    Workbooks(toolWorkbook).Activate
    ActiveSheet.Paste
    Application.CutCopyMode = False
    
    ActiveSheet.Name = tempName
    
    Workbooks(dataWorkbook).Activate
    ActiveWorkbook.Close False
    MsgBox "Data Import Complete", vbInformation, "Status"
End Sub

CODE in the userform
===================

Private Sub UserForm_Activate()
    Dim sh As Worksheet
    Workbooks(Module1.dataWorkbook).Activate
    For Each sh In ActiveWorkbook.Sheets
        frm_sheetSelect.lb_sheetNames.AddItem sh.Name
    Next sh
End Sub

Private Sub cmd_select_Click()
    If lb_sheetNames.Value <> "" Then
        Sheets(lb_sheetNames.Value).Activate
    Else
        MsgBox "Please select the sheet (containing the raw data) from the list to continue.", vbExclamation, "Status"
        Exit Sub
    End If
    Unload Me
    Call Module1.copyData
End Sub



Please put your thoughts and comments below so that I can improve.

THANKS EVERYONE.

SUBHAJIT.


Wednesday, February 28, 2018

Add data labels to dynamic scatter plot

Define 2 named ranges (Formula Tab > Name Manager > New):
-----------------------------------------------------------------------------
JobSat_Score
=OFFSET(Presentation!$B$7,0,0,COUNTA(Presentation!$B:$B)-5,1)

WorkLife_Score
=OFFSET(Presentation!$C$7,0,0,COUNTA(Presentation!$C:$C)-1,1)
Change the parameters according to your pivot design.

==================================================== 
Insert a scatter plot chart.
Add a series:
Series X values: ='Refresh Data Labels.xlsm'!JobSat_Score
Series Y values: ='Refresh Data Labels.xlsm'!WorkLife_Score
Adjust chart axis as per your requirement.

====================================================
For adding and refreshing data labels dynamically write this procedure and call it on a button click.
Sub refreshLabels()
    On Error Resume Next
    Dim counter As Integer, xValueFormula As String
    Application.ScreenUpdating = False
   
    ActiveSheet.ChartObjects(1).Activate
    xValueFormula = ActiveChart.SeriesCollection(1).Formula
   
    'getting the series name for X values
    xValueFormula = Mid(xValueFormula, InStr(1, xValueFormula, ",'", vbTextCompare) + 1)
    xValueFormula = Left(xValueFormula, InStr(1, xValueFormula, ",'", vbTextCompare) - 1)
   
    'Attach a label to each data point in the chart
    For counter = 1 To Range(xValueFormula).Cells.Count
        ActiveChart.SeriesCollection(1).Points(counter).HasDataLabel = False
        ActiveChart.SeriesCollection(1).Points(counter).HasDataLabel = True
        ActiveChart.SeriesCollection(1).Points(counter).DataLabel.Text = Range(xValueFormula).Cells(counter, 1).Offset(0, -1).Value
    Next counter
End Sub



DATA USED FOR EXAMPLE



Please put your thoughts and comments below so that I can improve.

THANKS EVERYONE.

SUBHAJIT.


Wednesday, December 13, 2017

Excel function for Rail Fence Cipher and Caesar Cipher

      Rail Fence Cipher:

·     
           Key and String as argument parameter from user,
o   =encode(input string, key)
o   =decode(encoded string, key)
·         If the user enters 2 then
o   There will be 2 rows:
o   fn encode_P1 ("MESSAGE IS THIS",2) will modify the input as:
MSAEI HSESG STI
M
S
A
E
I
H
S
E
S
G
S
T
I



o   fn decode_P1 ("MSAEI HSESG STI",2) will print the output as:

MESSAGE IS THIS

·         If the user enters 3 then
o   There will be 3 rows:
o   fn encode_P1 ("MESSAGE IS THIS",3) will modify the input as:
MAIHESG STISE S

M



A



I



H



E

S

G



S

T

I



S



E







S

o   fn decode_P1 ("MSAEI HSESG STI",3) will print the output as:
MESSAGE IS THIS

Caesar Cipher:

Eg. MESSAGE IS NOT THIS.
·       fn encode_P2("MESSAGE IS NOT THIS",3) will offset it by 3 ASCII characters.
Output:  PHVVDJH#LV#QRW#WKLV
fn decode_P2("PHVVDJH#LV#QRW#WKLV",3) will return the original statement.
Output: MESSAGE IS NOT THIS


Please put your thoughts and comments below so that I can improve.

THANKS EVERYONE.

SUBHAJIT.