你在过程quedingluru_Click()里,声明的变量dic、k,每当该过程结束,该变量就从内存里消失了,下次再次进入,该变量的值重新开始,上次的内容是不记忆的。
解决办法,你需要把它们声明为模块级变量。
Private dic As Object
Private YesNo As Boolean '开关状态
Private k As Long
注意:把 上面三行代码,放在整个代码窗口的最最上面的位置!!!!
完整代码如下:
Private dic As Object
Private YesNo As Boolean '开关状态
Private k As Long
Private Sub quedingluru_Click()
'使用YesNo的开关作用,是为了保证只运行一次CreateObject
If Not YesNo Then
YesNo = True
Set dic = CreateObject("Scripting.Dictionary")
End If
If dic.exists("TextBox1.Text &TextBox3.Text") Then
MsgBox "信息已存在"
Else
k = k + 1
dic.Add TextBox1.Text &TextBox3.Text, k
With Sheets("sheet1")
i = .[a1].CurrentRegion.Rows.Count + 1
.Cells(i, 1) = TextBox1.Text
.Cells(i, 2) = TextBox2.Text
.Cells(i, 3) = TextBox4.Text
.Cells(i, 4) = TextBox3.Text
End With
MsgBox "录入成功"
End If
End Sub
利用字典去重,下面是示例代码,去除第一列的重复项Sub Test() '利用字典去重,字典的特性是key值不能重复
Dim Dic, Arr
Dim i As Integer, r As Integer
Dim Str As String
r = Sheet1.Range("A65536").End(xlUp).Row
If r = 1 Then Exit Sub '如果第一列没有数据那么退出程序
Set Dic = CreateObject("scripting.dictionary") '创建字典对象
For i = 1 To r '将第一列数据添加到字典的key值中
Dic(CStr(Cells(i, 1))) = ""
Next
Arr = Dic.keys '返回字典key的数组
Set Dic = Nothing '销毁对象
Str = Join(Arr, ",") '将数组中的内容显示为一字符串
MsgBox Str
End Sub
举个例子,sheets(1)为1表数据源,sheets(2)为总表,两表之间通过a列判断是否重复
sub a()rowcount=sheets(1).[a90000].end(xlup).row
rowcount1=sheets(2).[a90000].end(xlup).row
num=1
for i=1 to rowcount
for k=1 to rowcount1
if sheets(1).range("a:" & i).value<>sheets(2).range("a:" & k).value then
sheets(2).range("a:" & rowcount1+num).value =sheets(1).range("a:" & i).value
num=num+1
end if
next
next
end sub
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)