VB 操作写入EXCEL文件保存时的问题

hfyanzi 2006-11-28 07:23:14
各位好:
原代码如下:
Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
cn.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=xx;Password=xx;Initial Catalog=dataservername;Data Source=data1"
cn.CursorLocation = adUseClient
cn.Open

Dim ExlApp As Excel.Application
Dim ExlBook As Excel.Workbook
Dim ExlSheet As Excel.Worksheet
Dim sql As String
Dim strdata As String

If Combo1.Text = "仓库编号" Then
sql = "select 列1,列2 from curr"
Else
sql = "select 列1,列2 from curr where curr.xx=1"
End If

Set rs = cn.Execute(sql)
If Not rs.EOF Then
Set ExlApp = CreateObject("Excel.Application")
ExlApp.Visible = False
Set ExlBook = ExlApp.Workbooks.Add
Set ExlSheet = ExlBook.Worksheets(1)
ExlSheet.Activate
Row = 3
With ExlSheet
strdata = Year(Now) & "-" & Right("00" & Month(Now), 2) & "-" & Right("00" & Day(Now), 2) & "-" & Right("00" & Hour(Now), 2) & "-" & Right("00" & Minute(Now), 2) & "-" & Right("00" & Second(Now), 2)
.Cells(1, 1) = "库存管理系统——分库库存"
.Cells(2, 1) = "数据导出日期:" & strdata
.Cells(3, 1) = "厂商货号"
.Cells(3, 2) = "数量"

.Cells.Font.Size = 9

Do While Not rs.EOF
Row = Row + 1
.Cells(Row, 1) = rs(0)
.Cells(Row, 2) = rs(1)
rs.MoveNext
Loop
.Range(.Cells(2, 1), .Cells(Row, 2)).Borders.LineStyle = xlContinuous
End With
CommonDialog1.Filter = "EXCEL文件(*.xls)|*.xls|"
CommonDialog1.DialogTitle = "保存文件"
CommonDialog1.ShowSave
If Len(CommonDialog1.FileName) = 0 Then Exit Sub
strExcelfile = CommonDialog1.FileName
ExlBook.Close
Set ExlSheet = Nothing
Set ExlBook = Nothing
ExlApp.Quit
Set ExlApp = Nothing
MsgBox "生成完毕,文件名:" & strExcelfile, vbOKOnly, "信息提示"
Else
MsgBox "没有符合条件的返还记录。", vbOKOnly, strmsg
End If

cn.Close
Set cn = Nothing

当我要导出数据到EXCEL的时候,调出存储对话框,如果保存的文件已存在,这个时候会软件会询问:当前位置发现已经存在名为“xxxx.xls”的文件。您希望将该文件替换掉吗?如果选是,软件不会出错,但如果选择否或者取消时就会出现以下错误:运行时错误'1004' 方法'~'作用于对象'~'失败。

请各位指教如何更改程序不让它出现这个错误。先谢了!
...全文
378 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
hfyanzi 2006-11-29
  • 打赏
  • 举报
回复
漏了,在strExcelfile = CommonDialog1.FileName之后加
ExlSheet.SaveAs strExcelfile
hfyanzi 2006-11-29
  • 打赏
  • 举报
回复
???
m00ners 2006-11-28
  • 打赏
  • 举报
回复
我眼里不好,怎么没看见保存的语句?
cangwu_lee 2006-11-28
  • 打赏
  • 举报
回复
之前自己判断,自己问用户是否删除。

2,462

社区成员

发帖
与我相关
我的任务
社区描述
VBA(Visual Basic for Applications)是Visual Basic的一种宏语言,是在其桌面应用程序中执行通用的自动化(OLE)任务的编程语言。
社区管理员
  • VBA
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧