Results 1 to 1 of 1

Help emailing a sheet that has a dynamic name.

Threaded View

  1. #1
    Forum Contributor
    Join Date
    02-16-2008
    Location
    Mansfield, TX
    Posts
    324

    Help emailing a sheet that has a dynamic name.

    Hello, I have put together a database program where a user imports several excel files, then clicks a button to extract several cells to a new sheet within the workbook that is then emailed. All of this is done by clicking three buttons on the top of one of the sheets. My problem lies in emailing the new sheet as it will be named something different everytime it is created. What I need help with is how do I get the code below to email the sheet that has just been created when there may be several sheets in the workbook? Would it be easier to modify the macro that creates the new sheet, then adds the control button and assigns it to the correct macro?

    I am using the code below to email the active sheet.

    Sub Mail_ActiveSheet()
    'Working in 97-2007
        Dim FileExtStr As String
        Dim FileFormatNum As Long
        Dim Sourcewb As Workbook
        Dim Destwb As Workbook
        Dim TempFilePath As String
        Dim TempFileName As String
    
        With Application
            .ScreenUpdating = False
            .EnableEvents = False
        End With
    
        Set Sourcewb = ActiveWorkbook
    
        'Copy the sheet to a new workbook
        ActiveSheet.Copy
        Set Destwb = ActiveWorkbook
    
        'Determine the Excel version and file extension/format
        With Destwb
            If Val(Application.Version) < 12 Then
                'You use Excel 97-2003
                FileExtStr = ".xls": FileFormatNum = -4143
            Else
                'You use Excel 2007, we exit the sub when your answer is
                'NO in the security dialog that you only see  when you copy
                'an sheet from a xlsm file with macro's disabled.
                If Sourcewb.Name = .Name Then
                    With Application
                        .ScreenUpdating = True
                        .EnableEvents = True
                    End With
                    MsgBox "Your answer is NO in the security dialog"
                    Exit Sub
                Else
                    Select Case Sourcewb.FileFormat
                    Case 51: FileExtStr = ".xlsx": FileFormatNum = 51
                    Case 52:
                        If .HasVBProject Then
                            FileExtStr = ".xlsm": FileFormatNum = 52
                        Else
                            FileExtStr = ".xlsx": FileFormatNum = 51
                        End If
                    Case 56: FileExtStr = ".xls": FileFormatNum = 56
                    Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
                    End Select
                End If
            End If
        End With
    
        '    'Change all cells in the worksheet to values if you want
        '    With Destwb.Sheets(1).UsedRange
        '        .Cells.Copy
        '        .Cells.PasteSpecial xlPasteValues
        '        .Cells(1).Select
        '    End With
        '    Application.CutCopyMode = False
    
        'Save the new workbook/Mail it/Delete it
        TempFilePath = Environ$("temp") & "\"
        TempFileName = "Credits Requested" & Format(Now, "dd-mmm-yy h-mm-ss")
    
        With Destwb
            .SaveAs TempFilePath & TempFileName & FileExtStr, _
                    FileFormat:=FileFormatNum
            On Error Resume Next
            .SendMail "dcgrove@nospam.com", _
                      "Credits Requested" & Format(Now, "dd-mmm-yy h-mm-ss")
            On Error GoTo 0
            .Close SaveChanges:=False
        End With
    
        'Delete the file you have send
        Kill TempFilePath & TempFileName & FileExtStr
    
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
        End With
    End Sub
    This is the code I am using to create the new sheet.

    Sub call_macros()
    Call Copy_With_AutoFilter1 'This creates the sheet
    Call column_delete 'This just deletes some unused columns in the new sheet
    Call Macro2 'This changes some formatting in the credit sheet
    End Sub
    Sub Copy_With_AutoFilter1()
    'Note: This macro use the function LastRow
       
        Dim My_Range As Range
        Dim CalcMode As Long
        Dim ViewMode As Long
        Dim FilterCriteria As String
        Dim CCount As Long
        Dim WSNew As Worksheet
        Dim sheetName As String
        Dim rng As Range
       
        'Set filter range on ActiveSheet: A1 is the top left cell of your filter range
        'and the header of the first column, D is the last column in the filter range.
        'You can also add the sheet name to the code like this :
        'Worksheets("Sheet1").Range("A1:D" & LastRow(Worksheets("Sheet1")))
        'No need that the sheet is active then when you run the macro when you use this.
        Set My_Range = Range("a2:s" & LastRow(ActiveSheet))
        My_Range.Parent.Select
    
        If ActiveWorkbook.ProtectStructure = True Or _
           My_Range.Parent.ProtectContents = True Then
            MsgBox "Sorry, not working when the workbook or worksheet is protected", _
                   vbOKOnly, "Copy to new worksheet"
            Exit Sub
        End If
    
    
        'Change ScreenUpdating, Calculation, EnableEvents, ....
        With Application
            CalcMode = .Calculation
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableEvents = False
        End With
        ViewMode = ActiveWindow.View
        ActiveWindow.View = xlNormalView
        ActiveSheet.DisplayPageBreaks = False
    
        'Firstly, remove the AutoFilter
        My_Range.Parent.AutoFilterMode = False
    
        'Filter and set the filter field and the filter criteria :
        'This example filter on the first column in the range (change the field if needed)
        'In this case the range starts in A so Field 1 is column A, 2 = column B, ......
        'Use "<>Netherlands" as criteria if you want the opposite
        My_Range.AutoFilter Field:=19, Criteria1:="=No"
    
        'If you want to filter on a cell value you can use this, use "<>" for the opposite
        'This example uses the activecell value
        'My_Range.AutoFilter Field:=1, Criteria1:="=" & ActiveCell.Value
    
        'This will use the cell value from A2 as criteria
        'My_Range.AutoFilter Field:=1, Criteria1:="=" & Range("A2").Value
    
        ''If you want to filter on a Inputbox value use this
        'FilterCriteria = InputBox("What text do you want to filter on?", _
         '                              "Enter the filter item.")
        'My_Range.AutoFilter Field:=1, Criteria1:="=" & FilterCriteria
    
        'Check if there are not more then 8192 areas(limit of areas that Excel can copy)
        CCount = 0
        On Error Resume Next
        CCount = My_Range.Columns(1).SpecialCells(xlCellTypeVisible).Areas(1).Cells.Count
        On Error GoTo 0
        If CCount = 0 Then
            MsgBox "There are more than 8192 areas:" _
                 & vbNewLine & "It is not possible to copy the visible data." _
                 & vbNewLine & "Tip: Sort your data before you use this macro.", _
                   vbOKOnly, "Copy to worksheet"
        Else
            'Add a new Worksheet
            Set WSNew = Worksheets.Add(After:=Sheets(ActiveSheet.Index))
    
            'Ask for the Worksheet name
            sheetName = "Credits Requested" & " " & Format(Now, "mmm-dd-yy")
    
            On Error Resume Next
            WSNew.Name = sheetName
            If Err.Number > 0 Then
                MsgBox "Change the name of sheet : " & WSNew.Name & _
                     " manually after the macro is ready. The sheet name" & _
                     " you fill in already exists or you use characters" & _
                     " that are not allowed in a sheet name."
                Err.Clear
            End If
            On Error GoTo 0
    
            'Copy/paste the visible data to the new worksheet
            My_Range.Parent.AutoFilter.Range.Copy
            With WSNew.Range("A1")
                ' Paste:=8 will copy the columnwidth in Excel 2000 and higher
                ' Remove this line if you use Excel 97
                .PasteSpecial Paste:=8
                .PasteSpecial xlPasteValues
                .PasteSpecial xlPasteFormats
                Application.CutCopyMode = False
                .Select
            End With
    
            ' If you want to delete the rows that you copy, also use this
            ' With My_Range.Parent.AutoFilter.Range
            '     On Error Resume Next
            '     Set rng = .Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count) _
            '               .SpecialCells(xlCellTypeVisible)
            '     On Error GoTo 0
            '     If Not rng Is Nothing Then rng.EntireRow.Delete
            ' End With
    
        End If
    
        'Close AutoFilter
        My_Range.Parent.AutoFilterMode = False
    
        'Restore ScreenUpdating, Calculation, EnableEvents, ....
        My_Range.Parent.Select
        ActiveWindow.View = ViewMode
        If Not WSNew Is Nothing Then WSNew.Select
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
            .Calculation = CalcMode
        End With
    
    End Sub
    
    
    Function LastRow(sh As Worksheet)
        On Error Resume Next
        LastRow = sh.Cells.Find(What:="*", _
                                After:=sh.Range("A1"), _
                                Lookat:=xlPart, _
                                LookIn:=xlValues, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlPrevious, _
                                MatchCase:=False).Row
        On Error GoTo 0
    End Function
    Attached Files Attached Files

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1