【发布时间】:2016-01-14 16:21:12
【问题描述】:
我在电子表格的 N 列中有一个颜色列表,在每一行/单元格中,该列表看起来类似于:
中蓝色=蓝色,浅蓝色=蓝色,中绿色=绿色,中橙色=橙色,中橙色=焦橙色,中灰色=不锈钢,深红色=焦橙色
我正在尝试查看每个单元格,找到 = 的所有实例并比较 = 之后的字符串直到下一个逗号(例如:它会查看“= ESP”)以查看该值是否在同一个单元格中多次出现(如果相同的值在不同的单元格中也没关系)。如果该值在同一个单元格中出现多次,我需要删除 = 之后的字符串并将其替换为 = 之前的字符串。完成所有这些之后,我还需要确保没有两个相似的值(“浅蓝色和中蓝色=浅蓝色”被认为是相同的)。所以,上面的字符串在正确的时候应该是这样的(留下尾随的逗号):
中蓝=蓝色,浅蓝=浅蓝,中绿=绿,中橙=橙,中橙=焦橙,中灰=不锈钢,深红=深红
'This is to figure out how many times to loop through a cell (Number of occurances
'of "=" in a given cell
'LEN(N2)-LEN(SUBSTITUTE(N2,"=",""))
Dim endRange As Integer
Dim equalCount As Integer
endRange = ActiveSheet.Cells(Rows.Count, "N").End(xlUp).Row
'Loop through each row in the column
For N = 2 To endRange
'Skip over a row if there is nothing in the cell
If ActiveSheet.Range("N" & N).Value <> "" Then
'Counts how many ='s there are in each cell
equalCount = Len(ActiveSheet.Range("N" & N).Value) - Len(Application.WorksheetFunction.Substitute(ActiveSheet.Range("N" & N).Value, "=", ""))
'Loops through a cell once for every ='s
For c = 1 To equalCount
Dim commaPos As Integer
Dim equalPos As Integer
'Find the next comma & that's immediately after the particular ='s
commaPos = FindN(",", ActiveSheet.Range("N" & N).Value, (c))
equalPos = FindN("=", ActiveSheet.Range("N" & N).Value, (c))
'Search the cell to see how many instances of the value between the ='s and ,
If (Application.WorksheetFunction.CountIf(InStr(ActiveSheet.Range("N" & N).Value, _
Mid(Right(ActiveSheet.Range("N" & N).Value, commaPos), Left(ActiveSheet.Range("N" & N).Value, equalPos), _
equalPos - commaPos)), ">1")) Then
MsgBox ("Found a Duplicate!")
End If
Next c
End If
Next N
End Sub
我不断收到“运行时错误 '13':类型不匹配”错误。另外,我很确定如果这确实有效,它仍然不会捕获字符串末尾的值,因为在最后一个 = 之后没有另一个逗号可以找到。
编辑
我的功能
Function FindN(sFindWhat As String, _
sInputString As String, N As Integer) As Integer
Dim J As Integer
Application.Volatile
FindN = 0
For J = 1 To N
FindN = InStr(FindN + 1, sInputString, sFindWhat)
If FindN = 0 Then Exit For
Next
End Function
【问题讨论】:
-
你在哪里得到错误,哪一行?
-
'If (Application.WorksheetFunction.CountIf(InStr(ActiveSheet.Range("N" & N).Value, _ Mid(Right(ActiveSheet.Range("N" & N).Value, commaPos), Left(ActiveSheet.Range("N" & N).Value, equalPos), _ equalPos - commaPos)), ">1")) Then' 它似乎指向该行中的 CountIf