我得到了列的总数,并尝试将其附加到字符串,这取决于列的数量,它是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()中的组合,然后删除重复项ya?如果我错了,请纠正我,但是我得到了应用程序定义的错误。
如何将动态列数设置为Array()?
答案 0 :(得分:4)
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
答案 1 :(得分:-1)
lcol = 130
Dim numOfCol() As Variant
Dim i As Long
ReDim numOfCol(0 To (lcol - 1))
For i = 0 To (lcol - 1)
numOfCol(i) = i + 1
Next i
ThisWorkbook.Worksheets("Header").Activate
ThisWorkbook.Worksheets("Header").Cells.RemoveDuplicates Columns:=(numOfCol), Header:=xlNo