在这里我再次询问有关VBA的问题,有时我们从我们的付款合作伙伴之一收到数据,这些数据在消费者的名字和后缀中包含额外不必要的逗号,例如Jr.Sr.等。我如何在代码中添加一个条件来限制这个?
这是 .txt 文件中带有额外逗号的数据示例: 15-1503-0533,巴罗纳,维吉利奥,JR.,202403,2024-03-21 19:50:59.000,972.26,0.00,0.00,08,A3E71D1641E8
该列应以“J”结尾,但由于名字和后缀之间有逗号,因此代码会自动分隔数据。
这是我当前的代码
Sub ImportTextFile()
Dim filePath As String
Dim ws As Worksheet
Dim targetCell As Range
Dim qt As QueryTable
Set ws = ActiveSheet
Set targetCell = ws.Range("A5")
filePath = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If filePath = "False" Then Exit Sub
ws.Cells.Clear
Set qt = ws.QueryTables.Add(Connection:="TEXT;" & filePath, Destination:=targetCell)
With qt
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.TextFileDecimalSeparator = True
.AdjustColumnWidth = False
.Refresh
End With
insert_cell
End Sub
我可以在代码中添加什么条件来自动忽略分隔名字和后缀的逗号?
我希望在上传后缀中带有额外逗号的 .txt 文件时得到这样的结果:
如有任何帮助,我们将不胜感激!
QueryTables
无法识别不同模式的数据Call CleanData(ws.Range("A5"))
Sub CleanData(StartCell As Range)
Dim i As Long, j As Long
Dim arrData, rngData As Range
Const COL_CNT = 10 ' modify as needed
Const COL_KEY = 4
Set rngData = StartCell.CurrentRegion
arrData = rngData.Value
If UBound(arrData, 2) > COL_CNT Then
For i = LBound(arrData) To UBound(arrData)
' COL_KEY is not a number
If Not IsNumeric(arrData(i, COL_KEY)) Then
' merge cell with left cell
arrData(i, COL_KEY - 1) = arrData(i, COL_KEY - 1) & _
" " & arrData(i, COL_KEY)
' Shift cells to left
For j = COL_KEY To UBound(arrData, 2) - 1
arrData(i, j) = arrData(i, j + 1)
Next j
arrData(i, UBound(arrData, 2)) = ""
End If
Next i
rngData.Value = arrData
End If
End Sub