我有一个vba脚本,用于将.CSV数据导入格式化的工作表中。它可以正常工作,但是突然挂掉了一部分垃圾字符,我要么需要找到另一种方法来删除这些字符,要么需要一种从不创建这些字符的CSV导入数据的方法。
很明显,我只是在使用别人的代码,试图学习如何真正地创建代码,但是我在这里头疼。
我尝试删除挂起脚本的代码,但是它随后以我的条件格式单元格称为无效的格式导入数据。我一直在寻找替代代码,但是我不确定垃圾字符是什么(可能是char(3),但这就是代码要删除的内容。
Sub Import()
Sheets("BATTERY").Select
ActiveSheet.Unprotect Password:="ACT2012"
Dim fn, e
Dim x, y, n As Long, txt As String, flg As Boolean
Dim i As Long, ii As Long, a(), maxCol As Long
fn = Application.GetOpenFilename("csv,*.csv", 1, "Open CSV",
MultiSelect:=True)
If Not IsArray(fn) Then Exit Sub
n = 201
For Each e In fn
If FileLen(e) > 0 Then
txt = CreateObject("Scripting.FileSystemObject") _
.OpenTextFile(e).ReadAll
x = Split(txt, vbCrLf)
ReDim a(1 To UBound(x) + 1, 1 To 20)
For i = 0 To UBound(x)
y = Split(CleanCSV(x(i), Chr(2), Chr(3)), ",")
maxCol = Application.Max(maxCol, UBound(y) + 2)
If maxCol > UBound(a, 2) Then
ReDim Preserve a(1 To UBound(a, 1), 1 To maxCol)
End If
For ii = 0 To UBound(y)
a(i + 1, ii + 1) = y(ii)
Next
Next
Sheets(3).Cells(n, 1).Resize(UBound(a, 1), maxCol).Value = a
n = n + UBound(a, 1)
End If
Next
With Sheets(3).UsedRange
.Replace Chr(3), ",", xlPart
.Replace Chr(3), vbNullString, xlPart
End With
End Sub
Function CleanCSV(ByVal txt As String, ByVal subComma As String, _
ByVal subDQ As String) As String
Dim m As Object
Static RegX As Object
If RegX Is Nothing Then Set RegX = CreateObject("VBScript.RegExp")
With RegX
.Pattern = "(^|,)(""[^""]+"")(,|$)"
Do While .test(txt)
Set m = .Execute(txt)(0)
txt = Application.Replace(txt, m.firstindex + 1, _
m.Length, m.submatches(0) & Replace(Replace(m.submatches(1), _
",", subComma), """", subDQ) & m.submatches(2))
Loop
End With
CleanCSV = txt
End Function
我希望将干净的数据粘贴到单元格A200下,但是代码现在在以下位置停止工作:
。替换Chr(3),“,”,xlPart
我尝试删除该行和下一行,但是我的数据如下:
2.83
这将删除我的工作表的其余部分。