8

假设 Excel 工作表有一个名为Student Names的列,并且该列有重复值。说,

Student
=======

Arup
John
Mike
John
Lisa
Arup

使用 VBScript,我怎样才能获得如下的唯一值?

Arup
John
Lisa
Mike
4

3 回答 3

13

用于获取唯一项的 VBScript 工具是一个字典:将所有项作为键添加到字典中,并且 dictionary.Keys() 将返回一个数组 - 每个定义项 - 唯一键。在代码中:

  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
于 2012-12-06T12:55:48.027 回答
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
于 2018-07-22T15:06:40.847 回答
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
于 2021-04-22T01:25:35.280 回答