Question

Email Selected Excel Sheets - Not Whole Workbook

Asked by: wileecoy

I know this solution is likely available as an answered question, but I cannot seem to navigate the site right now. CS is working on it, but I am willing to spend points for a custom answer.

I am looking for code to email selected Excel sheets (not the entire workbook) through Outlook and/or Outlook Express.

For example, if I have 8 sheets in a workbook, I would like the ability to select a single or multiple sheets within the workbook and email them, but not email the entire workbook.  I thought the easiest way to select the sheet(s) is to populate a listbox (that allows multiple selections) when the file is opened.  I have a 'Table of Contents' sheet that this would be located on..

The reason I cannot send the entire workbook is becuase all of the information is sensitive and cannot be distributed to everyone, but needs to be selectively sent to individuals.  Because of that, I cannot simply hide the sheets that I don't want the reader to see.

Thank you.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-12-14 at 06:24:50ID21664265
Tags

excel

,

email

,

sheet

Topic

Microsoft Excel Spreadsheet Software

Participating Experts
4
Points
500
Comments
18

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. returning number of sheets in a workbook
    Is there a formula I can use to return the total number of sheets in a the active workbook?
  2. list sheets in workbook -
    I have a workbook with 40 work sheets. Can I pull up a quick list of all the sheet names and print them? Thanks
  3. Adding sheets to an excel workbook...
    I have an excel workbook that has eight sheets to it. I need to insert a new sheet in the middle of the workbook but the move/copy button is gray and therefore I cannot add a new sheet. The workbook is password procteded. How can I add sheets?
  4. compare workbook add sheet or merge in sheet
    Hello Experts, I need help to merge data’s together. example Main Workbook Sheets Name = 002, 005, 008, 012, 028, 032, 033, 042, 063 etc,,, Workbook 1 Sheets Name =005, 008, 009, 029, 032, etc I need to merge another 4 workbook to the main one I would like to compare if work...
  5. List Sheets of Closed Workbook
    Here is a sub that will list all the sheets of a closed workbook in a listbox named "lstWS" on page "Main". However, there were several difficulties when creating it. First it gathers more than just sheets. Often it includes named ranges like Print_Area...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ampapaPosted on 2005-12-14 at 06:53:57ID: 15482215

 

by: wileecoyPosted on 2005-12-14 at 08:23:06ID: 15483125

Have you actually gotten this to work?  
I can't get it to go.
I get an error message:  The "SendUsing" configuration value is invalid.

I'm using Oulook.

Any ideas?

Also - I need the user to be able to choose sheet names from a listbox so the proper sheets are sent.  I didn't see anything on the link that addressed this.

I assume that a listbox with the available sheet names could work one of two ways.
1) use multi-select and a command button
2) use the _Click method of the first listbox that will populate a second listbox with the desired sheets, then a command button to send the email.

Also - The user will need to send multiple emails to several different people.  I need a way to attach the file to an open Outlook email form that will allow the user to input the names of the desired recipients (or some way to achieve the desired result of letting the user choose who to send each file to).  The example in your link had email addresses hard coded.

Thanks.

 

by: BTogniettiPosted on 2005-12-14 at 08:54:02ID: 15483440

I got this sub from an EE search a while back, I don't remember the author, but it works great;

Sub SendMail()
    Dim source As Range
    Dim ColumnCount As Long
    Dim FirstColumn As Long
    Dim ColumnWidthArray() As Double
    Dim lIndex As Long
    Dim lCount As Long
    Dim dest As Workbook
    Dim i As Long
    Dim strdate As String
    Dim OutApp As Outlook.Application
    Dim OutMail As Outlook.MailItem
    Dim strbody As String
    strTo = "first@emailaddress.com;second@emailaddress.com"
 
    Sheets("Summary").UsedRange.Select
    Set source = Nothing
    On Error Resume Next
    Set source = Selection.SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    If source Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protect, please correct and try again.", vbOKOnly
        Exit Sub
    End If
    If ActiveWindow.SelectedSheets.Count > 1 Or _
       Selection.Cells.Count = 1 Or _
       Selection.Areas.Count > 1 Then
        MsgBox "An Error occurred :" & vbNewLine & vbNewLine & _
               "You have more than one sheet selected." & vbNewLine & _
               "You only selected one cell." & vbNewLine & _
               "You selected more than one area." & vbNewLine & vbNewLine & _
               "Please correct and try again.", vbOKOnly
        Exit Sub
    End If
 
    Application.ScreenUpdating = False

    ColumnCount = Selection.Columns.Count
    FirstColumn = Selection.Cells(1).Column - 1
    ReDim ColumnWidthArray(1 To ColumnCount)
    lIndex = 0
    For lCount = 1 To ColumnCount
        If Columns(FirstColumn + lCount).Hidden = False Then
            lIndex = lIndex + 1
            ColumnWidthArray(lIndex) = Columns(FirstColumn + lCount).ColumnWidth
        End If
    Next lCount

    Set dest = Workbooks.Add(xlWBATWorksheet)
    source.Copy
    With dest.Sheets(1)
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        For i = 1 To lIndex
            .Columns(i).ColumnWidth = ColumnWidthArray(i)
        Next
    End With
   
    strdate = Format(Now, "ddd, dd-mmm-yyyy")
 
    strbody = "FileName " & strdate
   
    With dest
        .SaveAs strdate
        Set OutApp = CreateObject("Outlook.Application")
        Set OutMail = OutApp.CreateItem(olMailItem)
        With OutMail
            .To = strTo
            .Subject = "Subject " & strdate
            .Body = strbody
            .Attachments.Add dest.FullName
            .Send   'or use .Display
        End With
        Set OutMail = Nothing
        Set OutApp = Nothing
        .ChangeFileAccess xlReadOnly
        Kill .FullName
        .Close False
    End With
    Application.ScreenUpdating = True
End Sub

 

by: wileecoyPosted on 2005-12-14 at 09:16:05ID: 15483651

BTognietti,

The code looks good, but looks like it only applies to one sheet and not when multiple sheets are selected (in fact there is an error message when multiple sheets are selected).

I need the user to be able to select multiple sheets and send them to and individual or group via email.

In my example above I tried to throw out the idea of using a listbox to enumerate all sheets and use multi-selection in the listbox to allow the user to select the sheets desired in the email.

Then the user can press the command button to begin the email process.

The other point of concern, however, is that the user is sending each sheet or combination of sheets to a different user.  This requires that the user is able to select (dynamically) who each email is sent to.

This may require tapping into the address book in Outlook (since I did not include that in the question, I won't make it a requirement now - I'll post a different question for that).

I think this is headed the right direction - I actually tried it and it sent the email.

My guess is that I need to create the Outlook object like you did and apply it to the link that ampapa sent in the first response.

If that is the case, the only thing left would be to get some code for selecting the worksheets to be sent (in some dynamic way like the listbox I mentioned above) and then put all the code together.

Thanks - Wileecoy.

 

by: wileecoyPosted on 2005-12-14 at 12:09:22ID: 15485319

Guys,

I'm having problems copying multiple sheets dynamically (from link in first comment).  If I hard code them in it works, if I try to do anything with a string variable that mimics the exact text that is hard coded, it gives me an error - "Subscript out of range".

Any ideas on that, or any other ideas on putting together something that will allow me to dynamically select multiple sheets to copy?

I did get the email to work once the files are correctly selected.

Thanks - Norm.

 

by: jjjtuohyPosted on 2005-12-15 at 03:40:52ID: 15489411

This example creates a routing slip for Book1.xls and then sends the workbook to three recipients, one after another.

Workbooks("BOOK1.XLS").HasRoutingSlip = True
With Workbooks("BOOK1.XLS").RoutingSlip
    .Delivery = xlOneAfterAnother
    .Recipients = Array("Adam Bendel", _
        "Jean Selva", "Bernard Gabor")
    .Subject = "Here is BOOK1.XLS"
    .Message = "Here is the workbook. What do you think?"
End With
Workbooks("BOOK1.XLS").Route


If you want to examine the whole range of options available then have a look at the following 4 methods from my library: I know they're Access based but you will learn how to instantiate Outlook.

FOUR EMAIL METHODS


*************
1
*************

+++++++++++++++++++++++++++++++++++++++++++++++++++++=

'This code shows how to use VB to automate
' creating an Outlook Email. The main
' point to this is
'to show how you can use automation and
' still format your email body with bolding,
' font colors, sizes, etc.
'You must have the Outlook reference library
' checked for this code to use. Go to
' References and select the Microsoft
' Outlook Object Library.
'strings that store your variables for the
' email
'==================================

Dim mySubject As String
Dim myBody As String
Dim myText As String
Dim myEmail As String
Dim myCopy As String
Dim myBCopy As String
Dim myFormat As String

'this is where you can set up the format of the body.
myFormat = "MailFormat.rtf"
myFormat = "MailFormat.html"
myFormat = "MailFormat.Text"


'this is where you can enter your body message.
' You can add on later by appending
' with the & symbol
myBody = myBody & "You can use any <b>HTML tags</b> To format your body
message as you want." 'your subject goes here mySubject = "This is my
subject" 'declare a new instance of Outlook


=================================================

Dim myOutlook As New Outlook.Application
'set the variable as a new outlook app

Set myOutlook = New Outlook.Application
'set a variable as a new outlook mail item

Set myMessage = myOutlook.CreateItem(olMailItem)

==========
'this copies your body variable into the body' of the email.

''note the HTML declaration, as this allows
' you to use bold, italic, etc. tags in
' your body with Automation.
'This is the reason I created this code
' sample, so you can see how to format an
' email body any way you want
'using automation (you could use font tags
' and set font colors and everything this
' way.)

'Sets up the format of the email message whether to allow
' html etc.

================

myMessage.BodyFormat = myFormat

myMessage.Body = myBody


myMessage.Subject = mySubject

myMessage.To = myEmail

myMessage.Cc = myCopy

myMessage.Bcc = myBCopy


'adds attachments to your email

myMessage.Attachments.Add "C:\Temp\FileToAttach.txt"

'Repeat this line if there are more Attachments


''sends your email
myMessage.send

'Displays your email and then you would have to send it manually
myMessage.display

'Empties the Variables from memory
Set myMessage = Nothing
Set myOutlook = Nothing


'confirmation dialog box if you want to have one......
myResult = MsgBox("Your email has been sent.", vbOKOnly, "Email Sent")



//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
**********************
2
**********************

Here is another solution that is close to the previous, but less of the
other aspects of Outlook.

Following is an example of sending an email from Access using Outlook. This
one is using attachments and a second file to contain the directory of where
the attachments are for this version.

================================
Function SendThirdFinalOK()

Dim o
Dim m
Dim R As String
Dim E As String

' get directory path

Dim PathName As String
Dim CDirPart As String
Set db = CurrentDb()
Set AMName = db.OpenRecordset("CVS AM Directory Name")
AMName.MoveFirst
Let CDirPart = AMName![AM Directory]
Let PathName = AMName![CVS Path]
AMName.Close

Let R = [Forms]![Selected NCON SS]![Final OK to Disconnect Subform]![Circuit
ID]
Let E = "V:\TEAM FOLDERS\" & CDirPart & "\CVS\Final OK to Disconnect\Final
OK Letter.rtf"

Set o = CreateObject("Outlook.Application")
Set m = o.CreateItem(0)

m.To = "email1@yahoo.com"
'm.To = "email2@hotmail.com"
m.Subject = "Final OK to Disconnect " & R & " - Third and Final Request
for this Circuit **"
m.body = Chr(13) & Chr(13) & "Dave," & Chr(13) & Chr(13) & "This is the
final request for this Circuit." & Chr(13) & "If We do not receive a reply
by noon today we will cancel this disconnect per our agreement." & Chr(13) &
Chr(13) & Chr(13) & Chr(13)
m.attachments.Add E
'Repeat the above line if there are more Attachments
'm.Display
'use the above display line if you want to end up in the email but not
automatically send it.
' if you do the above the don't use the send line below.
m.Send
'If you want to just send it


End Function

==========================================

The security aspect of Outlook will require a response by the user to
actually send it.




//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
**********************
3
**********************



>
>Private Sub cmdEmail_Click()
>
>Below is the code I used to add to the command button on a form. You
>can modify the
>".Recipients.Add ("Christine") to reference the text box in your
>form with the correct
>E-mail address. As you can see, you can also add the body of the e-mail
>message.
>
>'***********************************************************************
>*********************
>Dim appOutlook As Outlook.Application
>Dim dbs As Database
>Dim fld As Outlook.MAPIFolder
>Dim flds As Outlook.Folders
>Dim itm As Outlook.AppointmentItem
>Dim itms As Outlook.Items
>Dim nms As Outlook.NameSpace
>Dim rst As Recordset
>Dim txt As Access.TextBox
>
>
>Set appOutlook = GetObject(, "Outlook.Application")
>Set nms = appOutlook.GetNamespace("MAPI")
>Set fld = nms.GetDefaultFolder(olFolderCalendar)
>If fld.DefaultItemType = olAppointmentItem Then
>
>Set itms = fld.Items
>'Set the appointment as a meeting so it can be sent to Christine
>Osborne.
>'This will give Christine notification when the item is created, and set
>'the dates on her calendar for a meeting.
>
>Set itm = itms.Add("IPM.Appointment")
>itm.MeetingStatus = olMeeting
> With itm
> .Recipients.Add ("Christine Osborn")
> .Subject = Nz(Me![EventType])
> .Start = Me![BeginEventDate]
> .End = Me![EndEventDate]
> .Location = Me![PresentationLocation]
> .Body = Me![Presenter] & " of the " & UCase(Me![Department]) &
>" department" & vbCrLf & _
> Me![Comments]
> .Send
> End With
> MsgBox ("Public Information Department has been notified of this
>event!")
>End If
>
>End Sub


//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

**********************
4
**********************

Private Sub SendMail()
On Error GoTo errMsg
Dim olApp As New Outlook.Application
Dim olNS As Outlook.NameSpace
Dim olAL As Outlook.AddressList
Dim olAE As Outlook.AddressEntry
Dim olMail As Outlook.MailItem
Dim aName() As Variant
Dim i As Integer

ReDim Preserve aName(7)
aName(0) = "afeld@governanceinstitute.com"
'aName(...) Put any other email addresses you need here

'Set olApp = New Outlook.Application
Set olMail = olApp.CreateItem(olMailItem)

For i = 0 To UBound(aName)
If aName(i) <> "" Then
olMail.Recipients.Add aName(i)
Else
Exit For
End If
Next i

olMail.Subject = "Subject"
olMail.Body = "Body"
'olMail.Attachments.Add "c:al.doc", , , "Provider List"
'olMail.Attachments.Add "c:\tmp\ProviderSummary.xls", , , "Provider
Summary"
olMail.Send

Set olApp = Nothing
Set olMail = Nothing
Exit Sub
errMsg:
MsgBox Error$(Err) & " " & err.description

End Sub


Thanks to christine Osborne, A Feld & Ron Nemec for their work
Regards,
John T

 

by: jjjtuohyPosted on 2005-12-15 at 03:43:36ID: 15489416

To select multiple worksheets use the Sheets method. You can enumerate the worksheets collection as an array ie Sheets(n)
Regards,
John T

 

by: wileecoyPosted on 2005-12-16 at 06:22:25ID: 15497623

jjjtuohy,

Thanks for posting code.  My problem at this point is more in my last posted comment of sending multiple sheets dynamically.

You posted a comment indicating to send an array.  Can you show me the code that would work.  I try it and still get 'Subscript out of range' errors.

Thanks - Wileecoy.

 

by: jjjtuohyPosted on 2005-12-16 at 14:54:51ID: 15501612

<<'Subscript out of range' >>
The Sheets array is one based not zero based.

eg to place the list of sheet names in column 1 of the first sheet:

For N = 1 To Sheets.Count
   Sheets(1).Cells(N, 1).Value = Sheets(N).Name
Next N

Regards,
John T

 

by: wileecoyPosted on 2005-12-19 at 05:28:39ID: 15510575

jjjtuohy,

I changed to 1 based - I still get the same error message.  Let me post my code and you all can let me know where I went wrong.

_______________________________________________________________

Sub cbSendEmail_Click()
    Dim WB1 As Workbook
    Dim WB2 As Workbook
    Dim WBname As String
    Dim OutApp As Outlook.Application
    Dim OutMail As Outlook.MailItem
 
    Application.ScreenUpdating = False
    Set WB1 = ActiveWorkbook

    'To get list of selected sheets
    Dim i As Integer
    Dim strText(9) As String        'only 8 worksheets in the file

    iCount = 1
    For i = 1 To (lbSheets.ListCount - 1)
        If lbSheets.Selected(i) = True Then
            strText(iCount) = lbSheets.List(i)
            iCount = iCount + 1
        End If
    Next i
   
    Sheets(Array(strText)).Copy
   
    Set WB2 = ActiveWorkbook
 
    ' It will save the new file with the ActiveSheet in C:/ with a Date and Time stamp
    WBname = "Part of " & WB1.Name & " " & Format(Now, "dd-mm-yy h-mm-ss") & ".xls"
    WB2.SaveAs "C:/" & WBname
     
    With WB2
        .SaveAs WBname
        Set OutApp = CreateObject("Outlook.Application")
        Set OutMail = OutApp.CreateItem(olMailItem)
        With OutMail
            .To = "email@aol.com"
            .CC = "email@aol.com"
            .BCC = "email@aol.com"
            '.From = "email@aol.com"
            .Subject = "Subject: " & WBname
            .Body = "Filename: " & WB2.Name 'strbody
            .Attachments.Add WB2.FullName
            .Send   'or use .Display
        End With
        Set OutMail = Nothing
        Set OutApp = Nothing
        .ChangeFileAccess xlReadOnly
        Kill .FullName
        .Close False
    End With

    Set WB1 = Nothing
    Set WB2 = Nothing
    Application.ScreenUpdating = True

End Sub

 

by: jjjtuohyPosted on 2005-12-20 at 17:15:55ID: 15523311

I assume you set references to outlook library.
Can you send the wbk to me because there are controls missing eg lbSheets
admin "at" HomeComputingSolutions "dot" ie
You may need to use Sheets(n).name where n is the sheet index number.

Instead of  .Attachments.Add WB2.FullName you can use multiple instances of  .Attachments.Add

The base code that works perfectly is:Sub Mail_ActiveSheet_Outlook_click()
Dim OutApp As Object
    Dim OutMail As Object
    Dim wb As Workbook
    Dim strdate As String
    strdate = Format(Now, "dd-mm-yy h-mm-ss")
    Application.ScreenUpdating = False
    ActiveSheet.Copy
    Set wb = ActiveWorkbook
    With wb
        .SaveAs "Part of " & ThisWorkbook.Name _
              & " " & strdate & ".xls"
        Set OutApp = CreateObject("Outlook.Application")
        Set OutMail = OutApp.CreateItem(0)
        With OutMail
            .To = "xxxxxxx@yyyyyy.net"
            .CC = ""
            .BCC = ""
            .Subject = "This is the Subject line"
            .Body = "Hi there"
            .Attachments.Add wb.FullName
            'You can add other files also like this
            '.Attachments.Add ("C:\test.txt")
            .Send   'or use .Display
        End With
        .ChangeFileAccess xlReadOnly
        Kill .FullName
        .Close False
    End With
    Application.ScreenUpdating = True
    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub


John T

 

by: wileecoyPosted on 2005-12-21 at 05:28:02ID: 15525955

The line: "ActiveSheet.Copy" still only copies one sheet into the file you are sending.

I'm trying to send multiple sheets, not just the active one.  That is my only remaining problem.  The rest of the code works ok.

In fact, if I hard code the line: "Sheets(Array("Sheet1", "Sheet3", "Sheet7")).Copy" it works, I just can't send it dynamically with variables.

Thanks,

Wileecoy (a/k/a still in need)

 

by: jjjtuohyPosted on 2005-12-21 at 12:11:29ID: 15529385

Have you tried enumerating the sheets collection and equating to a string array?

dim name_string()
redim  name_string(Sheets.Count)


For N = 1 To Sheets.Count
   set name_string(n)= Sheets(N).Name
etc etc
Next N

print routine........................

For P = 1 To Sheets.Count
   set name_string(P)= nothing
etc etc
Next P

Regards,
John t

 

by: wileecoyPosted on 2005-12-21 at 14:12:22ID: 15530328

Ok - that isn't really working either.

Maybe you can help me do it one sheet at a time.

Something like the following in a For Next loop:
Sheet("sheet1").copy  ' puts it to a new sheet.
Sheet("sheet2").copy after:=Sheet("sheet1")

I actually have tried to do that, but the 'copy after' doesn't seem to go from one workbook to the other - it appears (by examples in help and by having problems with the code) that it is only for moving sheets within the same file.  I was hoping that I'm missing something.

My deal is this:
1.  I know what sheets are to be email becuase the user selected them in a listbox
2.  I can loop through and get each of those sheets
3.  I can send any single sheet to a new workbook with Sheet("SheetName").copy
4.  I can save the file, mail the file, close the file
5.  I cannot seem to send multiple sheets to a new workbook unless I a) hard code them or b) pre-determine them (I need to allow user to choose which sheets get emailed and they may not be the same sheets each time).

This seems like it should be possible, but is turning into more than I anticipated.

 

by: jjjtuohyPosted on 2005-12-22 at 12:43:32ID: 15537556

No. Do copy, print, delete and then repeat
J

 

by: wileecoyPosted on 2005-12-22 at 12:45:50ID: 15537577

jjjtuohy,

I don't want to print, I want to email.  Maybe I don't understand.

Wileecoy

 

by: jeveristPosted on 2005-12-23 at 09:22:48ID: 15543425

Hi Wileecoy,

It looks like you just about had it - just a few tweeks.  Try this:

Sub cbSendEmail_Click()
    Dim WB1 As Workbook
    Dim WB2 As Workbook
    Dim WBname As String
    Dim OutApp As Outlook.Application
    Dim OutMail As Outlook.MailItem
    Dim iCount As Long
 
    Application.ScreenUpdating = False
    Set WB1 = ActiveWorkbook

    'To get list of selected sheets
    Dim i As Integer
    Dim strText() As String        'only 8 worksheets in the file

    iCount = 0
    For i = 0 To (lbSheets.ListCount - 1)
        If lbSheets.Selected(i) = True Then
            ReDim Preserve strText(iCount)
            strText(iCount) = lbSheets.List(i)
            iCount = iCount + 1
        End If
    Next i
   
    WB1.Sheets(strText).Copy
   
    Set WB2 = ActiveWorkbook
 
    ' It will save the new file with the ActiveSheet in C:/ with a Date and Time stamp
    WBname = "Part of " & WB1.Name & " " & Format(Now, "dd-mm-yy h-mm-ss") & ".xls"
    WB2.SaveAs "C:\" & WBname
    'WB2.SaveAs "C:/" & WBname
     
    With WB2
        .SaveAs WBname
        Set OutApp = CreateObject("Outlook.Application")
        Set OutMail = OutApp.CreateItem(olMailItem)
        With OutMail
            .To = "email@aol.com"
            .CC = "email@aol.com"
            .BCC = "email@aol.com"
            '.From = "email@aol.com"
            .Subject = "Subject: " & WBname
            .Body = "Filename: " & WB2.Name 'strbody
            .Attachments.Add WB2.FullName
            .Send   'or use .Display
        End With
        Set OutMail = Nothing
        Set OutApp = Nothing
        .ChangeFileAccess xlReadOnly
        Kill .FullName
        .Close False
    End With

    Set WB1 = Nothing
    Set WB2 = Nothing
    Application.ScreenUpdating = True

End Sub


Jim

 

by: wileecoyPosted on 2005-12-23 at 12:33:13ID: 15544392

Ok!  It works!

I split the points becuase of contributions from more than one expert.

My base code was from ampapa, jjjtuohy stuck with me and helped me modify it, and jeverist plugged in the (critical) missing piece.

Thanks to all.

Wileecoy.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...