文档保存
求记事本保存代码?
程序代码:Private Sub mnuFileSave_Click() '保存菜单
'用应用程序向导生成的
Dim sFile As String
If Left$(ActiveForm.Caption, 8) = "Document" Then '无文件名
With dlgCommonDialog '设置保存文件对话框
.DialogTitle = "保存"
.CancelError = False
'ToDo: 设置 common dialog 控件的标志和属性
.Filter = "所有文件 (*.*)|*.*"
.ShowSave '显示对话框
If Len(.FileName) = 0 Then '如果返回的文件名为空白,如取消了
Exit Sub '放弃操作
End If
sFile = .FileName '读出文件名来
End With
If Dir(sFile) <> "" Then
If MsgBox(sFile & " 文件已存在,是否覆盖?", vbOKOnly, "文件存在") = vbOK Then
Call savetext(sFile, ActiveForm.Text1.Text) '调用保存
ActiveForm.Caption = sFile '把文件名放在子窗口的标题上
End If
Else
Call savetext(sFile, ActiveForm.Text1.Text) '调用保存
ActiveForm.Caption = sFile '把文件名放在子窗口的标题上
End If
Else
sFile = ActiveForm.Caption '从窗体标题上读文件名
Call savetext(sFile, ActiveForm.Text1.Text) '调用保存
End If
End Sub
Private Sub savetext(sFileName As String, ByRef sStr As String)
'sFileName 文件名
'sStr 文件内容,按地址传递,也就是传递指针
Const TMPFile = "~tmp.tmp" '临时文件名
On Error GoTo err1:
Dim lFree As Long
lFree = FreeFile '取下一个文件名
Open TMPFile For Output As lFree '打开文件
Print #lFree, sStr '保存内容
Close #lFree
If Dir(sFileName) <> "" Then '如果原文件名存在
Kill sFileName '删掉
End If
FileCopy TMPFile, sFileName '复制生成新文件
'不使用改名就防止临时文件与目标文件不在一个路径下,就会改名失败
Kill TMPFile '删临时文件
Exit Sub
err1:
MsgBox "保存时出现错误,未能成功保存", vbCritical, "保存文件时错误"
End Sub
