我在excel vba中編寫了一個宏/一段代碼,用於將當前工作表發送到特定的.txt格式的電子郵件,但是當我收到電子郵件時,有幾個不需要的在文件中列出的逗號我只是試圖找到一段代碼,當文件在電子郵件中發送時將刪除這些額外的逗號。我目前有另一個宏創建打開和讀取文件,並刪除不需要的逗號,但我不得不保存電子郵件附件,而我想直接收到乾淨的.txt文件直接到我的電子郵件。Excel VBA /宏從.txt文件中刪除不需要的逗號
我收到的當前.txt文件看起來像;
S99,2602,7/12/2017,
10405,PUSH NUT PLAIN 1/4,2.000,EACH
WVC424,CORD 2.2MM E/S CHESTNUT,3.800,MTR
,,,
而我需要它看起來像;
S99,2602,7/12/2017
10405,PUSH NUT PLAIN 1/4,2.000,EACH
WVC424,CORD 2.2MM E/S CHESTNUT,3.800,MTR
它被讀入我們的系統。
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
我目前得到的代碼已在上面列出。
我猜不需要的逗號在每行的右側。這些表示Excel *認爲正在使用的空列,並且必須包含在導出中。隔離您想要導出的區域或編寫一個獨立生成CSV的循環。 – Jeeped