2017-07-12 294 views
0

我在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 

我目前得到的代碼已在上面列出。

+2

我猜不需要的逗號在每行的右側。這些表示Excel *認爲正在使用的空列,並且必須包含在導出中。隔離您想要導出的區域或編寫一個獨立生成CSV的循環。 – Jeeped

回答

0

請嘗試將其保存爲文本格式?

FileFormat:=xlText

+0

這會刪除所有逗號,而不僅僅是不需要的號碼。 –

+0

您收到額外逗號的原因很可能是因爲數據末尾有單元格,它們中有空格。在保存文件之前,您需要處理數據並去除其中包含空格的單元格。 – braX

+0

您可能還想了解如何將一定範圍的單元格保存到CSV文件中,但無論哪種方式,您都必須具有一些可以檢測數據末尾位置的代碼。 – braX

0

您可以只複製使用範圍(未測試):

ThisWorkbook.Worksheets(wsName).UsedRange.CurrentRegion.Copy 
With Workbooks.Add 
    .Sheets(1).Paste 
    .SaveAs csvFiles(i), FileFormat:=xlCSV 
    .Close False 
End With 

或粘貼值,不進行格式化(也未測試):

ThisWorkbook.Worksheets(wsName).UsedRange.Copy 
With Workbooks.Add 
    ActiveCell.PasteSpecial xlPasteValues 
    .SaveAs csvFiles(i), FileFormat:=xlCSV 
    .Close False 
End With 
+0

我測試了這兩種方法都沒有效果,第一段代碼只是給出了相同的輸出,第二段代碼刪除了每個逗號。 –