如何使用VBscript从值列表中获取唯一值?

时间:2012-12-06 11:59:05

标签: vbscript

假设Excel工作表有一个名为学生姓名的列,并且该列具有重复值。说,

Student
=======

Arup
John
Mike
John
Lisa
Arup

使用VBScript,我如何获得如下的唯一值?

Arup
John
Lisa
Mike

3 个答案:

答案 0 :(得分:10)

用于获取唯一项的VBScript工具是一个字典:将所有项添加为字典和字典的键.Keys()将返回 - 每个definitionem - 唯一键的数组。在代码中:

  Dim aStudents : aStudents = Array("Arup", "John", "Mike", "John", "Lisa", "Arup")
  WScript.Echo Join(aStudents)
  Dim aUniqStudents : aUniqStudents = uniqFE(aStudents)
  WScript.Echo Join(aUniqStudents)

' returns an array of the unique items in for-each-able collection fex
Function uniqFE(fex)
  Dim dicTemp : Set dicTemp = CreateObject("Scripting.Dictionary")
  Dim xItem
  For Each xItem In fex
      dicTemp(xItem) = 0
  Next
  uniqFE = dicTemp.Keys()
End Function

输出:

Arup John Mike John Lisa Arup
Arup John Mike Lisa

答案 1 :(得分:0)

或者,由于源数据在Excel电子表格中,因此您可以使用SQL填充ADODB记录集:

Option Explicit

Dim filePath, sheetName
filePath = "C:\path\to\excel\workbook.xlsx"
sheetName = "Sheet1"

Dim connectionString
connectionString = _
    "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "Data Source=""" & filePath & """;" & _
    "Extended Properties=""Excel 12.0;HDR=No"""

Dim sql
sql = "SELECT DISTINCT Student FROM [" & sheetName & "$]"

Dim rs
Set rs = CreateObject("ADODB.Recordset")
rs.Open sql, connectionString

Do Until rs.EOF
    WScript.Echo rs("StudentName")
Loop

答案 2 :(得分:0)

如果您不需要 Dictionary,您可以使用以下命令将数组中的每个元素与其自身进行比较。

Info = Array("Arup","John","Mike","John","Lisa","Arup")

x = 0
z = ubound(Info)
Do
x = x + 1
Do
z = z - 1
If x = z Then
Info(x) = Info(z)
ElseIf Info(x) = Info(z) Then
Info(x) = ""
End If
Loop Until z=0
z = ubound(Info)
Loop Until x = ubound(Info)
For each x in Info 
If x <> "" Then
Unique = Unique & Chr(13) & x
End If
Next

MsgBox Unique