2017-10-19 88 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