excel VBA 窗体 录入

最近开始学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
Set rng = Columns(6).Find(DTPicker1.Value & ComboBox2.Text & ComboBox1.Text)
If rng is not nothing then
    Msgbox "记录已存在,不能提交!"
    Exit sub
End If

当然,也可以用字典对象来做,更简单。


还有,那段查找B列最后一个空单元的循环可以简化为一句代码,如下:

i = Range("B65536").End(xlUp).Offset(1,0).Row

List 控件的 RowSource 属性可以和工作表单元格关联,然后仿照前面判断重复的代码,进行记录的定位,然后进行修改并保存。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-04-18
1.你可以在do loop循环中加入判断语句
Do
i = i + 1
if Cells(i, 2) = DTPicker1.Value _and '日期
Cells(i, 3) = ComboBox2.Text _and '时间
Cells(i, 4) = ComboBox1.Text _and '人员
Cells(i, 5) = TextBox1.Text then '事项
msgbox "已存在!"

exit do
end if

Loop Until Cells(i, 2) = ""

2.你可以在窗体上再添加个texbox1控件,然后对Listview1进行筛选
Dim i As Long
Dim s1 As String
Dim itm As ListItem
s1 = Me.TextBox1.Text
Me.ListView1.ListItems.Clear
For i = 2 To Sheet1.Range("a65536").End(xlUp).Row
If Sheet1.Cells(i, 1) Like s1 & "*" Then
Set itm = ListView1.ListItems.Add
itm.Text = Sheet1.Cells(i, 1)
itm.SubItems(1) = Sheet1.Cells(i, 2)
End If
Next i

关于listview表头、列宽、颜色等设置可以参考以下代码:

With ListView1
.View = lvwReport
.ColumnHeaders.Add 1, , Sheet1.Cells(1, 1), 80
.ColumnHeaders.Add 2, , Sheet1.Cells(1, 2), 346.75
.Gridlines = True
.FullRowSelect = True
.HotTracking = True
.Font.Size = 13
.ForeColor = RGB(65, 135, 245)
.Font.Bold = True
End With追问

谢谢回复得这么详细,不过对于我这种初学者有点深奥,呵呵,能不能麻烦你帮我把我之前的语句和打算增加了这个条件语句写在一起,谢谢

追答

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

本回答被提问者和网友采纳
第2个回答  2014-04-18
真的不知道 你好强大 啊
相似回答