簡體   English   中英

如何使用vba從excel文件中刪除逗號?

[英]How do i remove commas from an excel file using vba?

我正在將自動作為 .txt 放入文件夾的文件轉換為 csv 文件。 現在這個文件中有一些名字在末尾包含一個逗號。 我想知道是否有辦法刪除這個逗號。

這是當前的腳本:

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

使用替換功能。

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

我們也可以通過這種方式嘗試我們的VBA代碼

Sub test()
For Each cell In ActiveSheet.UsedRange.Cells
cell.Value = Replace(cell.Value, ",", " ")
Next
End Sub 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM