是否有任何Collection对象的方法我可以用其他值替换字符串?

时间:2012-12-26 12:44:59

标签: excel-vba vbscript vba excel

我正在寻找VBScript中的任何集合对象,它能够在一组字符串中找到特定的字符串(可以是Excel行内容)。如果目标字符串中的搜索值出现多次,那么也是匹配的值应该由重新放置的值替换。功能应该类似于Excel中的Application.Match()

修改

  Elements to be removed -> (14,25,99,78)' in an 1D Array
  ArrayList objects hold -> (11,14,23,14,56,67,25,14,112,21,25,14,99,44,33,99,78)
  Fatser process I want which will process the above Arraylist object and give me the 
  list as - > (11,23,56,67,112,21,44,33)

谢谢, 奥雅纳

1 个答案:

答案 0 :(得分:1)

如果字符串可以用逗号分隔,那么使用split将其放入arrayList中。然后,您可以搜索ArrayList,因为它允许您添加重复的项目。

您可以在方便级别使用Replace

Dim strInput as String
strInput = "mystring values are too many values
Replace (strInput, "values", "items")
Msgbox  strInput '-- returns "mystring items are too many items"

根据数组中的值删除ArrayList中的元素的代码段: 请根据您的数据需求更改代码。登录保持不变。

Sub removeInLists()
Dim vArray As Variant
Dim d As Object
Dim arrayList As Object
Dim i As Integer

Set d = CreateObject("Scripting.Dictionary")
Set arrayList = CreateObject("System.Collections.ArrayList")

'--populate array from Range with deletion keywords
vArray = Application.WorksheetFunction.Transpose(Sheets(1).Range("B2:B10"))

arrayList.Add "countries"
arrayList.Add "cities"
arrayList.Add "numbers"
arrayList.Add "hola"
arrayList.Add "decimals"
arrayList.Add "hola"
arrayList.Add "decimals"
arrayList.Add "numbers"

'--put arrayList into the dictionary to get unique values
For i = 0 To arrayList.Count - 1
    If Not d.Exists(arrayList(i)) Then
        d.Add arrayList(i), i
    End If
Next

'--output original arrayList
Sheets(1).Range("C2").Resize(arrayList.Count, _
1) = Application.Transpose(arrayList.toArray)

'-- remove data
For i = LBound(vArray) To UBound(vArray)
    '--remove from dictionary
    If d.Exists(vArray(i)) Then
        d.Remove (vArray(i))
    End If
    '--remove from arrayList
    If arrayList.Contains(vArray(i)) Then
        arrayList.Remove vArray(i)
    End If
Next i

'-- if you want you may save it as a array list or keep it as a dicionary or an array
'--vArray = d.Keys

'--output ArrayList
Sheets(1).Range("D2").Resize(arrayList.Count, _
1) = Application.Transpose(arrayList.toArray)

'-- output final dictionary after deletions
Sheets(1).Range("E2").Resize(d.Count) = Application.Transpose(d.keys)

Set arrayList = Nothing
Set d = Nothing
End Sub

工作表中的输出:

enter image description here