【发布时间】:2017-07-13 04:43:01
【问题描述】:
我在 excel vba 中编写了一个宏/一段代码,以将当前工作表发送到 .txt 格式的特定电子邮件,但是当我收到电子邮件时,文件中列出了几个不需要的逗号,我只是想当文件在电子邮件中发送时,可能会找到一段代码来删除这些额外的逗号。我目前创建了另一个宏,它打开并读取文件并删除不需要的逗号,但我必须先保存电子邮件附件,而我只想将干净的 .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 的循环。