各位大侠,我遇到一个小问题。我想单击command1,临时生成一个word文档,并把text1的内容存进去,这样写的代码,可是运行出错,麻烦各位高手指点一下。Private Sub Command1_Click() Dim wordApp As Word.Application Dim wordDoc As Word.Document Set wordApp = CreateObject("Word.Application") wordApp.Documents.Add wordDoc.Content = Text1.Text wordApp.Visible = True End Sub另外,我如果还有一个数组s(1 to 3,1 to 5),也想把它的数据逐个存进word,该怎么实现呢?
Dim cn As New ADODB.Connection ‘定义数据库 Dim rs As New ADODB.Recordset Dim scan As String ‘存储查找数据库 Dim Appword As Word.Application ’定义WORD模型变量 Dim Newword As Word.Document Set Appword = New Word.Application Set Newword = Appword.Documents.Add(App.Path + "/stencil" + "/stencil.doc") ‘这里是打开模版文档。stencil是模板的意思。可根据自己的需要替换。 Appword.Visible = False ‘隐藏WORD。导出时不在任务栏出现WORD文档。 Appword.WindowState = wdWindowStateMinimize scan = text2(0).Text '按编号搜索需要导出word的记录,一次只能导出一条记录 rs.CursorLocation = adUseClient ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + App.Path + "/data.mdb;Jet OLEDB:Database Password=harry2000" cn.Open ConnectionString rs.Open "select * from ADMIN where 编号 = '" & scan & "'", cn, adOpenKeyset, adLockOptimistic‘查找需要导出的记录 If rs.RecordCount = 0 Then ’如果不存在该记录 MsgBox "请在左边选择需要导出的记录" Appword.Documents.Close Appword.Quit Exit Sub Else ‘如果存在记录则运行以下代码 With Newword ’设置模版表格和在表格中填入数据库内容。 .Tables(1).Cell(1, 1).Range.Text = (Format(rs!日期, "yyyy年mm月dd日")) .Tables(2).Cell(3, 4).Range.Text = (rs!时间) '可以根据自己的需要设置填写内容。 End With Appword.ChangeFileOpenDirectory (App.path+ "/导出WORD文件夹") Appword.ActiveDocument.SaveAs FileName:=(App.path+ "/导出WORD文件夹/" & rs!姓名 & Format(Now, "yyyy-mm-dd") & ".doc"), FileFormat:=wdFormatDocument, LockComments:=False, Password:="", AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:=False Appword.Documents.Close Appword.Quit MsgBox "导出成功," & rs!姓名 & Format(Now, "yyyy-mm-dd") & "的资料保存于" & vbCrLf & vbCrLf & App.path + "/导出WORD文件夹" End If Set Appword = Nothing ‘交还控制权 Set Newword = Nothing Newword.Close rs.Close ’关闭数据库
应该这样写比较好Private Sub Command1_Click() Dim wordApp As New Word.Application Dim wordDoc As Word.Document Set wordDoc = wordApp.Documents.Add wordDoc.Content = Text1.Text wordApp.Visible = True wordDoc.SaveAs ("c:\newword.doc")'保存成文件 wordDoc.Close Set wordApp = Nothing End Sub二维数组的话做个循环,把数组的内容组成一个字符串,如:for i = 1 to 3 for j = 1 to 5 str = str & s(i,j) next jnext i再用上面的代码,把worddoc.content=那个字符串