我得到了总列数,并尝试将其附加到字符串中,根据列数,它是 1,2,3,4,5。
Sub DeleteHighlightedRecords()
numofCol = ""
For i = 1 To lcol
numofCol = numofCol & "," & i
Next i
numofCol = Mid(numofCol, 2)
ThisWorkbook.Worksheets(1).Cells.RemoveDuplicates Columns:=Array(numofCol), Header:=xlNo
End Sub
我上面的代码将匹配我放入 Array() 中的组合,然后删除重复项,是吗?如果我错了,请纠正我,但是我收到了应用程序定义的错误。
如何将动态列数设置到 Array() 中?
Array(1,2,3)
与 Array("1,2,3")
不同。第一个将生成一个包含 1,2 和 3 的 3 元素数组,第二个将生成一个包含字符串 "1,2,3"
的 1 元素数组。
要创建实际的数组,我们可以执行以下操作:
Dim numOfCol() As Variant 'normally I would choose Long instead of variant but that gave a type mismatch error
Dim i As Long 'always use "Option Explicit" at the top of your module!
ReDim numOfCol(0 To (lcol - 1)) 'has to be 0-based for RemoveDuplicates
For i = 0 To (lcol - 1)
numOfCol(i) = i + 1
Next i
现在好像使用
Variant
数组而不是 Long
数组并使用基于 0 的数组还不够,RemoveDuplicates
显然也无法处理作为变量而不是值的引用传递的参数。要将变量作为值而不是引用传递,请将其括在括号中。这会导致变量被计算然后传递给函数。
ThisWorkbook.Worksheets(1).Cells.RemoveDuplicates Columns:=(numOfCol), Header:=xlNo
调暗范围 Dim varArray 作为变体 暗淡指数一样长
子宏1()
Set rng = ActiveSheet.Range("A2").CurrentRegion
'find the number of columns and enter into the array
ReDim varArray(rng.Columns.count - 1)
index = 0
'loop through range and load values to the array
Do Until index > rng.Columns.count - 1
varArray(index) = index + 1
index = index + 1
Loop
'remove duplicates
rng.RemoveDuplicates Columns:=(varArray), Header:=xlYes
结束子