在Excel Visual Basic中从CSV中删除连续的重复值

在一个Excel 2007的VBmacros,我试图做的是采取逗号单独的string,拆分,然后减less它,删除重复的连续值。 所以“2,2,2,1,1”变成“2,1”,或者“3,3,3,2,3,3,3”变成“3,2,3”。

它看起来应该工作,但是当它到达“If currentVal.equals(prevVal)= False Then”时,它是一个运行时错误424,“Object required”。

自从我做了任何VB以来,这一直是永远的,那就是VP6。

Sheets("Sheet1").Select Range("I1").Select Dim data() As String Dim currentVal, prevVal As String Dim output As String Dim temp As Boolean Do Until Selection.Value = "" data = Split(Selection, ",") output = "" prevVal = "" For Each elem In data currentVal = CStr(elem) If currentVal.equals(prevVal) = False Then output = output + elem + "," End If Next elem Selection.Value = output Selection.Offset(1, 0).Select Loop 

有几个问题。 首先,你不能使用:

 Dim currentVal, prevVal As String 

您必须使用:

 Dim currentVal as String Dim prevVal As String 

要么:

 Dim currentVal as String, prevVal as String 

…因为不能在VBA中快捷地inputtypes。 其次,string不是在VBA中的对象,所以没有.equals(或任何其他方法)。 你要:

 If currentVal <> prevVal Then 

最后,您需要在循环结束时设置prevVal,否则代码将无法正常工作。

编辑这里有一些工作代码:

 Dim data() As String Dim currentVal As String, prevVal As String Dim output As String Dim temp As Boolean Do Until Selection.Value = "" data = Split(Selection, ",") output = "" prevVal = "" For Each elem In data currentVal = CStr(elem) If currentVal <> prevVal Then output = output + elem + "," End If prevVal = currentVal Next elem Selection.Value = output Selection.Offset(1, 0).Select Loop 

我build议使用具有正则expression式的变体数组来最大化您的方法的效率和速度。 像这样的东西

更新:在我自己的build议上采取其他地方的代码现在testing多个单元格应用变体数组之前

  Sub Clear() Dim ws As Worksheet Dim rng1 As Range Dim X Dim lngRow As Long Dim objRegex Set objRegex = CreateObject("vbscript.regexp") Set ws = Sheets("Sheet1") Set rng1 = ws.Range(ws.[i1], ws.Cells(Rows.Count, "I").End(xlUp)) With objRegex .Global = True .Pattern = "(\d)(,(\1))+" If rng1.Cells.Count > 1 Then X = rng1 For lngRow = 1 To UBound(X) X(lngRow, 1) = .Replace(X(lngRow, 1), "$1") Next lngRow rng1 = X Else rng1.Value = .Replace(rng1.Value, "$1") End If End With End Sub 

您可以使用字典对象,特别是因为您正在将数字移动到文本文件,无关紧要,它们不被视为数字本身。 看到这个问题