I've written a macro/piece of code in excel vba to send the current worksheet to a specific email in .txt format but when I receive the email there are several unneeded commas listed in the file I'm just trying to possibly find a piece of code that will remove these extra commas when the file is sent over in the email. I currently have another macro created which opens and reads the file and removes the unwanted commas but i am having to save the email attachment first whereas I'd like to just receive the clean .txt file directly to my email.
The current .txt file I am receiving looks like;
S99,2602,7/12/2017,
10405,PUSH NUT PLAIN 1/4,2.000,EACH
WVC424,CORD 2.2MM E/S CHESTNUT,3.800,MTR
,,,
whereas I need it to look like;
S99,2602,7/12/2017
10405,PUSH NUT PLAIN 1/4,2.000,EACH
WVC424,CORD 2.2MM E/S CHESTNUT,3.800,MTR
For It to be read into our system.
Sub EmailAsCSV()
'
' EmailAsCSV Macro
'
Dim csvFiles(1 To 3) As String, i As Integer
Dim wsName As Variant
Dim OutApp As Object, OutMail As Object
i = 0
For Each wsName In Array("Sheet1") 'sheet names to be emailed - CHANGE THE SHEET NAMES
i = i + 1
csvFiles(i) = ThisWorkbook.Path & "\" & wsName & ".txt"
ThisWorkbook.Worksheets(wsName).Copy
ActiveWorkbook.SaveAs csvFiles(i), FileFormat:=xlCSV
ActiveWorkbook.Close False
Next
'Email the .csv files
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = ThisWorkbook.Worksheets("Sheet2").Range("E1").Value 'cell containing email address - CHANGE THE SHEET NAME AND CELL
.CC = ""
.BCC = ""
.Subject = "Order"
.Body = "This email contains 1 file attachment with an order."
.Attachments.Add csvFiles(1)
.Send
End With
Set OutMail = Nothing
Set OutApp = Nothing
'Delete the .csv files
Kill csvFiles(1)
'
End Sub
Sub test()
Dim fn As String, txt As String
fn = Application.GetOpenFilename("TextFiles,*.txt")
If fn = "" Then Exit Sub
txt = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
With CreateObject("VBScript.RegExp")
.Global = True: .MultiLine = True
.Pattern = ",+$"
Open Replace(fn, ".txt", "_Clean.txt") For Output As #1
Print #1, .Replace(txt, "")
Close #1
End With
End Sub
The code I have currently got is listed above.
Try saving it in text format instead?
FileFormat:=xlText
You can copy just the used range (not tested):
ThisWorkbook.Worksheets(wsName).UsedRange.CurrentRegion.Copy
With Workbooks.Add
.Sheets(1).Paste
.SaveAs csvFiles(i), FileFormat:=xlCSV
.Close False
End With
or paste the values without formatting (also not tested):
ThisWorkbook.Worksheets(wsName).UsedRange.Copy
With Workbooks.Add
ActiveCell.PasteSpecial xlPasteValues
.SaveAs csvFiles(i), FileFormat:=xlCSV
.Close False
End With
Related
I have a workbook that I am trying to email with macros. This way the recipient will also be able to use the macros that are included with the workbook. This will make office life easier for my company. I have tried setting the saved file name to .xlsm, but that causes an error.
This is my code (which is adapted from sources online)
Sub MailGo()
'Variable declaration
Dim oApp As Object, _
oMail As Object, _
WB As Workbook, _
FileName As String, MailSub As String, MailTxt As String
'Turns off screen updating
Application.ScreenUpdating = False
'Makes a copy of the active sheet and save it to
'a temporary file
ActiveSheet.Copy
Set WB = ActiveWorkbook
FileName = "Text.xls"
On Error Resume Next
Kill "C:\" & FileName
On Error GoTo 0
WB.SaveAs FileName:="C:\Users\Public\Documents" & FileName
'Creates and shows the outlook mail item
Set oApp = CreateObject("Outlook.Application")
Set oMail = oApp.CreateItem(0)
With oMail
.To = "wesley.x.sherow#us.tel.com"
.Cc = ""
.Bcc = ""
.Subject = "LotInput"
.Body = "LotInput"
.Attachments.Add WB.FullName
.Display
.send
End With
'Deletes the temporary file
WB.ChangeFileAccess Mode:=xlReadOnly
Kill WB.FullName
WB.Close SaveChanges:=False
'Restores screen updating and release Outlook
Application.ScreenUpdating = True
Set oMail = Nothing
Set oApp = Nothing
End Sub
you need to also include this argument in your .SaveAs line.
FileFormat:=xlOpenXMLWorkbookMacroEnabled
I have an Excel workbook, with several worksheets in it. Each worksheet is a document I would like to email separately.
I have the workbook on a Windows XP SP3 machine running Office 2007. The VBA code works perfectly, and I can email each individual worksheet.
I need to run this on a Windows 7 or Windows 10 PC, again with Office 2007. This is where I get the error:
Sub EmailWithOutlook()
Dim oApp As Object
Dim oMail As Object
Dim WB As Workbook
Dim FileName As String
Dim wSht As Worksheet
Dim shtName As String
Application.ScreenUpdating = False
' Make a copy of the active worksheet
' and save it to a temporary file
ActiveSheet.Copy
Set WB = ActiveWorkbook
FileName = WB.Worksheets(1).Name
On Error Resume Next
Kill "C:\" & FileName
On Error GoTo 0
WB.SaveAs FileName:="C:\" & FileName
'Create and show the Outlook mail item
Set oApp = CreateObject("Outlook.Application")
Set oMail = oApp.CreateItem(0)
With oMail
'Uncomment the line below to hard code a recipient
'.To = "testuser#test.com"
'Uncomment the line below to hard code a subject
'.Subject = "Subject Line"
'Uncomment the lines below to hard code a body
'.body = "Dear John" & vbCrLf & vbCrLf & _
'"Here is the file you asked for"
.Attachments.Add WB.FullName
.Display
End With
'Delete the temporary file
WB.ChangeFileAccess Mode:=xlReadOnly
Kill WB.FullName
WB.Close SaveChanges:=False
'Restore screen updating and release Outlook
Application.ScreenUpdating = True
Set oMail = Nothing
Set oApp = Nothing
End Sub
The routine stops on the line containing the following:
WB.SaveAs FileName:="C:\" & FileName
What am I missing?
Windows users by default do not have permission to write at C:\ root directory.
Solutions:
Use a sub directory where the user has permission to write
Change user permission to gain write access at C:\ (not recommended)
I've created a excel spreadsheet template for our customers to populate and send back to us. I want to manually select their populated data and save it as a .csv to import into another piece of software. I, first, attempted this by recording a macro. This didn't work because different customers send different numbers of records.
I've tried snippets of code from online research and came up with this.
Sub Select_To_CSV()
Dim rng As Range
Dim myrangearea()
Range(ActiveCell, ActiveCell.End(xlDown).End(xlToRight)).Select
Dim myPath As String, v
myPath = "p:\" & _
Format(Date, "yyyymmdd") & ".csv"
'myPath = "x:\" & Format(Date, "yyyymmdd") & ".csv"
v = SaveAs(myPath)
If v <> False Then ThisWorkbook.SaveAs v
End Sub
Function SaveAs(initialFilename As String)
On Error GoTo EndNow
SaveAs = False
With Application.FileDialog(msoFileDialogSaveAs)
.AllowMultiSelect = False
.ButtonName = "&Save As"
.initialFilename = initialFilename
.Title = "File Save As"
'.Execute
.Show
SaveAs = .SelectedItems(1)
End With
EndNow:
End Function
Sub Select_To_CSV()
Dim rng As Range
Dim myrangearea()
Range(ActiveCell, ActiveCell.End(xlDown).End(xlToRight)).Select
Dim myPath As String, v
myPath = "p:\" & _
Format(Date, "yyyymmdd") & ".csv"
'myPath = "x:\" & Format(Date, "yyyymmdd") & ".csv"
v = SaveAs(myPath)
If v <> False Then ThisWorkbook.SaveAs v
End Sub
This worked really well except when I went back to look at the .csv in the folder it was the same worksheet not the selected columns.
Ultimately what I am looking to do is,
Manually select the columns I want
Run a macro that converts the selected columns to a .csv
Have the Save As Dialog Box appear
Navigate to the certain folder I want.
Here you go:
Sub MacroMan()
ChDrive "P:" '// <~~ change current drive to P:\
Dim copyRng As Excel.Range
Dim ThisWB As Excel.Workbook
Dim OtherWB As Excel.Workbook
Dim sName As String
'// set reference to the 'Master' workbook
Set ThisWB = ActiveWorkbook
'// assign selected range to 'copyRng'
Set copyRng = Application.InputBox(Prompt:="Select range to convert to CSV", Type:=8)
'// If the user selected a range, then proceed with rest of code:
If Not copyRng Is Nothing Then
'// Create a new workbook with 1 sheet.
Set OtherWB = Workbooks.Add(1)
'// Get A1, then expand this 'selection' to the same size as copyRng.
'// Then assign the value of copyRng to this area (similar to copy/paste)
OtherWB.Sheets(1).Range("A1").Resize(copyRng.Rows.Count, copyRng.Columns.Count).Value = copyRng.Value
'// Get save name for CSV file.
sName = Application.GetSaveAsFilename(FileFilter:="CSV files (*.csv), *.csv")
'// If the user entered a save name then proceed:
If Not LCase(sName) = "false" Then
'// Turn off alerts
Application.DisplayAlerts = False
'// Save the 'copy' workbook as a CSV file
OtherWB.SaveAs sName, xlCSV
'// Close the 'copy' workbook
OtherWB.Close
'// Turn alerts back on
Application.DisplayAlerts = True
End If
'// Make the 'Master' workbook the active workbook again
ThisWB.Activate
MsgBox "Conversion complete", vbInformation
End If
End Sub
This will allow you to manually select a range (including entire columns). It will then transfer said range onto a new sheet, save that sheet as a CSV, using the Save As dialog, and then close it afterwards.
I am new to VBA and am writing a macro. The purpose is to iterate through a list of spreadsheets (I have two sets saved in the same directory and each set has a specific naming convention). One set is named as "GenLU_xx" and the other is named as "LUZ_Summary_xx". The 'xx' in each name refers to a name e.g. Calgary. So I would have two different spreadsheets for Calgary (LUZ_Summary_Calgary & GenLU_Calgary).
The Macro needs to open each spreadsheet starting with "LUZ" add a value to G1. I have accomplished this first part by modifying code I found here: http://www.thespreadsheetguru.com/the-code-vault/2014/4/23/loop-through-all-excel-files-in-a-given-folder
The macro asks the user to identify the directory the spreadsheets are stored in and then loops through ones starting with "LUZ*".
The code is:
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "LUZ*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(fileName:=myPath & myFile)
'Add GEN_LU_ZN to column G1
wb.Worksheets(1).Range("G1").Value = "GEN_LU_ZN"
'Save and Close Workbook
wb.Close SaveChanges:=True
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
What I need for it to do from this point is copy two specific columns from each of the spreadsheets starting with "GenLU" and paste them into sheet 2 of the corresponding spreadsheet.
For example column C & E need to be copied from "GenLU_Calgary_2008" to the second sheet in the corresponding spreadsheet "LUZ_Summary_Calgary_2015". The code needs to somehow match up the spreadsheets using the name (in this case Calgary) and it needs to do this for all the spreadsheets.
Sorry for the extremely long question, but I'm hoping some can help a VBA newb out. I've searched quite a bit and while I have found the code to copy from sheet to sheet or workbook to workbook I am having trouble achieving what I need to. Any help will be much appreciated!
It is hard to test something without having any files, but you can try the following as part of your code:
Dim i As Integer
Dim wb1 As Workbook, wb2 As Workbook
Dim MyAr() As String: MyAr = Split("Calgary,XXX,YYY", ",")
For i = LBound(MyAr) To UBound(MyAr)
Do While myFile <> ""
If myFile Like "GenLU" & "*" & MyAr(i) Then
Set wb1 = Workbooks.Open(Filename:=myPath & myFile)
Exit Do
End If
Loop
Do While myFile <> ""
If myFile Like "LUZ_Summary" & "*" & MyAr(i) And Not wb1 Is Nothing Then
Set wb2 = Workbooks.Open(Filename:=myPath & myFile)
wb2.Worksheets(1).Columns(3).Value = wb1.Worksheets(1).Columns(3).Value
wb2.Worksheets(1).Columns(5).Value = wb1.Worksheets(1).Columns(5).Value
wb1.Close
wb2.Save
wb2.Close
Exit Do
End If
Loop
Set wb1 = Nothing
Next i
Note that you did not provide information which Worksheet you are working on, so I assume its always Worksheets(1). Column C = Columns(3). MyAr() is a String array to store the countries.
I have a list of accounts and relevant information that I have to split up and send specific accounts to certain people. This has to be done about 50 times. I already have a program setup that will filter, copy the data to a new file, and save. Is there a way to set it up to then email this file based on a list of contacts?
Each account is covered by a region, so I have a list which has the region and the contact's email. In the macro that splits by the regions, it has an array of these regions so is some kind of lookup possible from the list of contacts?
Code:
Sub SplitFile()
Dim rTemp As Range
Dim regions() As String
Set rTemp = ThisWorkbook.Sheets("Combined").Range("AH2:AH1455")
regions = UniqueItems(rTemp, False)
For N = 1 To UBound(regions)
Set wb = Workbooks.Add
ThisWorkbook.Sheets("DVal").Copy _
after:=ActiveWorkbook.Sheets("Sheet1")
With ThisWorkbook.Sheets("Combined")
.AutoFilterMode = False
' .AutoFilter
.Range("A1:BP1455").AutoFilter Field:=34, Criteria1:=regions(N)
Application.DisplayAlerts = False
.Range("A1:BP1455").Copy wb.Sheets("Sheet1").Range("A1")
Application.DisplayAlerts = True
For c = 1 To 68
wb.Sheets("Sheet1").Range("A1:BP2694").Columns(c).ColumnWidth = .Columns(c).ColumnWidth
Next c
End With
With wb
.Sheets("Sheet1").Activate
.SaveAs Filename:="H:\" & regions(N) & " 14-12-11"
.Close True
End With
Set wb = Nothing
Next N
End Sub
I am assuming you want to do it programmaticaly using VB, you can do something like
Dim msg As System.Web.Mail.MailMessage = New System.Web.Mail.MailMessage()
msg.From = "noone#nobody.com"
msg.To = "someone#somewhere.com"
msg.Subject = "Email with Attachment Demo"
msg.Body = "This is the main body of the email"
Dim attch As MailAttachment = New MailAttachment("C:\attachment.xls")
msg.Attachments.Add(attch)
SmtpMail.Send(msg)
If you're having trouble with the above, my mail macro is different; this is used with excel 2007:
Sub Mail()
Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strbody = "To Whom It May Concern:" & vbNewLine & vbNewLine & _
"This is a test!" & vbNewLine & _
"This is line 2" & vbNewLine & _
"This is line 3" & vbNewLine & _
"This is line 4"
On Error Resume Next
With OutMail
.to = "anyone#anywhere.com"
.cc = ""
.BCC = ""
.Subject = "This is only a test"
.Body = strbody
'You can add an attachment like this
'.Attachments.Add ("C:\test.txt")
.Send 'or use .Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Jon
I am assuming the following.
1) Regions are in Col AH
2) Contacts are in Col AI
3) UniqueItems() in your code removes duplicates?
Please try the below code. I have commented the code so please go through them and make relevant changes. Especially to the part where you save the File. I have used Late Binding with Outlook.
NOTE: I always test my code before posting but in the current scenario I cannot so do let me know if you find any errors.
Option Explicit
Sub SplitFile()
'~~> Excel variables
Dim wb As Workbook, wbtemp As Workbook
Dim rTemp As Range, rng As Range
Dim regions() As String, FileExt As String, flName As String
Dim N As Long, FileFrmt As Long
'~~> OutLook Variables
Dim OutApp As Object, OutMail As Object
Dim strbody As String, strTo As String
On Error GoTo Whoa
Application.ScreenUpdating = False
Set wb = ActiveWorkbook
'~~> Just Regions
Set rTemp = wb.Sheets("Combined").Range("AH2:AH1455")
'~~> Regions and Email address. We wil require this later
'~~> Tofind email addresses
Set rng = wb.Sheets("Combined").Range("AH2:AI1455")
regions = UniqueItems(rTemp, False)
'~~> Create an instance of outlook
Set OutApp = CreateObject("Outlook.Application")
For N = 1 To UBound(regions)
Set wb1 = Workbooks.Add
wb.Sheets("DVal").Copy after:=wb1.Sheets(1)
With wb.Sheets("Combined")
.AutoFilterMode = False
With .Range("A1:BP1455")
.AutoFilter Field:=34, Criteria1:=regions(N)
'~~> I think you want to copy the filtered data???
.Offset(1, 0).SpecialCells(xlCellTypeVisible).Copy _
wb1.Sheets("Sheet1").Range("A1")
For c = 1 To 68
wb1.Sheets("Sheet1").Range("A1:BP2694").Columns(c).ColumnWidth = _
wb.Columns(c).ColumnWidth
Next c
End With
End With
'~~> Set the relevant Fileformat for Save As
' 51 = xlOpenXMLWorkbook (without macro's in 2007-2010, xlsx)
' 52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2010, xlsm)
' 50 = xlExcel12 (Excel Binary Workbook in 2007-2010 with or without macro's, xlsb)
' 56 = xlExcel8 (97-2003 format in Excel 2007-2010, xls)
FileFrmt = 52
Select Case FileFrmt
Case 50: FileExt = ".xlsb"
Case 51: FileExt = ".xlsx"
Case 52: FileExt = ".xlsm"
Case 56: FileExt = ".xls"
End Select
'~~> Contruct the file name.
flName = "H:\" & regions(N) & " 14-12-11" & FileExt
'~~> Do the save as
wb1.SaveAs Filename:=flName, FileFormat:=FileFrmt
wb1.Close SaveChanges:=False
'~~> Find the email address
strTo = Application.WorksheetFunction.VLookup(regions(N), rng, 2, 0)
'~~> Create new email item
Set OutMail = OutApp.CreateItem(0)
'~~> Create the body of the email here. Change as applicable
strbody = "Dear Mr xyz..."
With OutMail
.To = strTo
.Subject = regions(N) & " 14-12-11" '<~~ Change subject here
.Body = strbody
.Attachments.Add flName
'~~> Uncomment the below if you just want to display the email
'~~> and comment .Send
'.Display
.Send
End With
Next N
LetContinue:
Application.ScreenUpdating = True
'~~> CleanUp
On Error Resume Next
Set wb = Nothing
Set wb1 = Nothing
Set OutMail = Nothing
OutApp.Quit
Set OutApp = Nothing
On Error GoTo 0
Whoa:
MsgBox Err.Description
Resume LetContinue
End Sub