最近开始学VBA,做了一个简单的录入窗体,自动将录入日期、时间、人员、事项等信息添加到工作表中,
代码如下
Private Sub CommandButton2_Click()
Dim i As Integer
i = 1
Do
i = i + 1
Loop Until Cells(i, 2) = ""
If ComboBox1.Text = "" Or ComboBox2.Text = "" Then
MsgBox "时间和人员不能缺项!", vbInformation, "提示"
Else
Cells(i, 2) = DTPicker1.Value '日期
Cells(i, 3) = ComboBox2.Text '时间
Cells(i, 4) = ComboBox1.Text '人员
Cells(i, 5) = TextBox1.Text '事项
End If
End Sub
两个问题:
1、现在想要追加一个判断条件,即如果日期、时间、人员三项内容与工作表中已有的完全一致,则出现提示:记录已存在,并且不能提交,多条件判断不会用,请高手指教。
2,如果想要把录入的内容用listview显示在右边(如下图),增加修改和查询功能,同时保存到工作表中,怎么操作?
先谢了
建议:
添加一个辅助数据: Cells(i, 6) = DTPicker1.Value & ComboBox2.Text & ComboBox1.Text
用作索引字段
然后在写入工作表之前,增加一个判断:
Dim rng as Range当然,也可以用字典对象来做,更简单。
还有,那段查找B列最后一个空单元的循环可以简化为一句代码,如下:
i = Range("B65536").End(xlUp).Offset(1,0).RowList 控件的 RowSource 属性可以和工作表单元格关联,然后仿照前面判断重复的代码,进行记录的定位,然后进行修改并保存。
谢谢回复得这么详细,不过对于我这种初学者有点深奥,呵呵,能不能麻烦你帮我把我之前的语句和打算增加了这个条件语句写在一起,谢谢
追答1.就是在中间加上一行来判断是否在EXCEL中已存在当前输入的内容
Private Sub CommandButton2_Click()
Dim i As Integer
i = 1
Do
i = i + 1
if Cells(i, 2) = DTPicker1.Value and Cells(i, 3) = ComboBox2.Text and Cells(i, 4) = ComboBox1.Text then
msgbox "记录已存在!"
exit sub
end if
Loop Until Cells(i, 2) = ""
If ComboBox1.Text = "" Or ComboBox2.Text = "" Then
MsgBox "时间和人员不能缺项!", vbInformation, "提示"
Else
Cells(i, 2) = DTPicker1.Value '日期
Cells(i, 3) = ComboBox2.Text '时间
Cells(i, 4) = ComboBox1.Text '人员
Cells(i, 5) = TextBox1.Text '事项
End If
End Sub