来信已收到。
这是我修改后的代码,请复制运行即可:
Option Explicit
Dim myCon As New ADODB.Connection
Dim myRs As New ADODB.Recordset
Private Sub Command1_Click()
Dim XueHao, XingMing As String
XueHao = Text1.Text
XingMing = Text2.Text
If Trim(XueHao) = "" Or Trim(XingMing) = "" Then
MsgBox "学生档案资料不能为空,请填写!"
Exit Sub
End If
myCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb;"
myRs.Open "select * from 学生档案 where 学号='" & Trim(XueHao) & "' and 姓名='" & Trim(XingMing) & "'", myCon
If myRs.EOF = False Then
MsgBox "该学生档案已经存在,请重新输入!"
myRs.Close
myCon.Close
Text1.SetFocus
Exit Sub
End If
myRs.Close
myRs.Open "学生档案", myCon, 3, 2
myRs.AddNew
myRs.Fields("学号") = Text1.Text
myRs.Fields("姓名") = Text2.Text
myRs.Update
myRs.Close
myCon.Close
MsgBox "添加成功!"
Adodc1.RecordSource = "select * from 学生档案 order by 姓名 "
'DataGrid1.DataSource = Adodc1.Recordset
Me.Adodc1.Refresh
Me.DataGrid1.Refresh
Text1.Text = ""
Text2.Text = ""
End Sub
Private Sub Command2_Click()
Dim i As Integer, j As Integer
Dim xlApp
Dim xlBook
Dim xlSheet
Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False
Set xlBook = xlApp.Workbooks.Open(App.Path & "\123.xls") '打开模板文件,请修改
xlApp.Visible = False
Set xlSheet = xlBook.Worksheets("工作表1") '设置活动工作表,请修改
With Adodc1
DataGrid1.Visible = False
DataGrid1.Tag = "busy"
.Recordset.MoveFirst
For j = 0 To .Recordset.RecordCount - 1
xlSheet.Cells(j + 4, 4) = .Recordset.Fields(0)
xlSheet.Cells(j + 4, 2) = .Recordset.Fields(1)
DoEvents
.Recordset.MoveNext
Next
xlBook.SaveAs FileName:=App.Path & "\1.xls" '保存模板文件,请修改
xlBook.Close (True)
xlApp.Quit
Set xlApp = Nothing
End With
DataGrid1.Tag = ""
DataGrid1.Visible = True
MsgBox "数据文件已成功写入EXCEL模板文件中!"
End Sub
Private Sub DataGrid1_RowColChange(LastRow As Variant, ByVal LastCol As Integer)
If DataGrid1.Tag = "busy" Then Exit Sub
Me.Adodc1.RecordSource = "select * from 学生档案 where 学号 = '" & Trim(DataGrid1.Row) & "'"
Text1.Text = Me.Adodc1.Recordset.Fields("学号")
Text2.Text = Me.Adodc1.Recordset.Fields("姓名")
End Sub
Private Sub Form_Load()
'Text3.Text = DataGrid1.Bookmark '获取当前指定的行号
'Me.Adodc1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\db1.mdb;Persist Security Info=False"
'Me.Adodc1.RecordSource = "select * from 学生档案"
End Sub
温馨提示:答案为网友推荐,仅供参考