2017-10-19 122 views
0

我正在將一個文件作爲.txt文件自動放入一個csv文件。現在這個文件上有一些名稱,最後包含一個逗號。我想知道是否有刪除這個逗號的方法。如何從使用vba的excel文件中刪除逗號?

這是當前腳本:

Option Explicit 

On Error Resume Next 
xlApp.DisplayAlerts = False 
XlApp.SetWarnings False 
Dim xlApp, xlBook, xlSheet 

Const xlCSV = 6 

On Error Resume Next 
xlApp.DisplayAlerts = False 
XlApp.SetWarnings False 

Set xlApp = CreateObject("Excel.Application") 

Set xlBook = xlApp.Workbooks.Open(FileLocation:\& "filename.txt", , , 6, , , , , "|") 

Set xlSheet = xlBook.worksheets.item(1) 



XlApp.SetWarnings False 

On Error Resume Next 

xlApp.DisplayAlerts = False 

xlSheet.Range("B:B").Delete 

xlSheet.Range("C:C").Delete 

xlSheet.Range("F:H").Delete 

xlSheet.Range("G:K").Delete 

xlSheet.Range("P:Q").Delete 

xlSheet.Range("A1").EntireRow.Insert 

xlSheet.Cells(1,1).Value = "name1" 

xlSheet.Cells(1,2).Value = "name2" 

xlSheet.Cells(1,3).Value = "name3" 

xlSheet.Cells(1,4).Value = "name4" 

xlSheet.Cells(1,5).Value = "here is where the comma appears for some files" 

xlSheet.Cells(1,6).Value = "name5" 

xlSheet.Cells(1,7).Value = "name6" 

xlSheet.Cells(1,8).Value = "name7" 

xlSheet.Cells(1,9).Value = "name8" 

xlSheet.Cells(1,10).Value = "name9" 

xlSheet.Cells(1,11).Value = "name10" 

xlSheet.Cells(1,12).Value = "name11" 

xlSheet.Cells(1,13).Value = "name0" 

xlSheet.Cells(1,14).Value = "name22" 

xlSheet.Cells(1,15).Value = "name24" 




xlApp.DisplayAlerts = False 

xlBook.Saveas "Filelocation:\filename.csv", xlCSV 

xlApp.DisplayAlerts = False 

xlApp.Quit 

回答

1

使用替換功能。

xlSheet.Cells(1,5).Value = replace(xlSheet.Cells(1,5).Value, ",", "") 

要應用此操作,您需要將新值分配給單元格。 像這樣將通過E欄所有使用的細胞

For Each c In Cells.Range("E1:E" & Cells(ActiveSheet.Rows.Count, "E").End(xlUp).Row) 
c.Value = Replace(c.Value, ",", "") 
Next c 
+0

只是爲了澄清「xlsheet.cells(1,5)」對應列E:在此列的一些記錄有一個逗號,這就是我需要刪除。如果我應用該函數將會像替換(xlSheet.Range(「E:E」)。Value =「,」,「」)但它無法運行腳本 –

+0

您是否只想爲單元格E1執行此操作? (Cells(1,5))那麼這很好,否則你需要編寫一些代碼來遍歷你想從中刪除逗號的列或行或區域。 – mooseman