如何在Excel VBA 中读写word文档 步骤

如题所述

参考这个:
Sub ExcelToWord() '  利用Word程序创建文本文件
    Dim WordApp As Object
    Dim Records As Integer, i As Integer
    Dim Region As String, SalesAmt As String, SalesNum As String, strTitle As String

    Set WordApp = CreateObject("Word.Application") '创建word对象
    Records = Application.CountA(Sheets("sheet1").Range("A:A")) 'A列数据个数

    WordApp.Documents.Add '新建文档


    '写Title
        strTitle = Cells(1, 5)
        With WordApp.Selection
            .Font.Size = 28
            .ParagraphFormat.Alignment = 1  '左对齐0  居中1 右对齐2
            .Font.Bold = True
            .TypeText Text:=strTitle
            .TypeParagraph
        End With
        
    '写内容
    For i = 1 To Records
        'Region = Data.Cells(i, 1).Value '将第一列某行的值赋值给变量
        Region = Cells(i, 1)
        'SalesNum = Data.Cells(i, 2).Value '获取该行B列数据
        SalesNum = Cells(i, 2)
        'SalesAmt = Data.Cells(i, 3).Value '获取该行C列数据
        SalesAmt = Cells(i, 3)
        
        
        
                
        With WordApp.Selection
                
                .Font.Size = 14 '设置字体字号
                .Font.Bold = True '字体粗
                .ParagraphFormat.Alignment = 0 '设置对齐
                .TypeText Text:=Region & SalesNum
                .TypeParagraph

                .Font.Size = 12 '设置字体
                .ParagraphFormat.Alignment = 0 '设置对齐
                .Font.Bold = False '字体不加粗
                .TypeText Text:=vbTab & SalesAmt
                .TypeParagraph '回车
                .TypeParagraph '回车
                
        End With
    Next i

    WordApp.ActiveDocument.SaveAs Filename:="AAA" '保存文件
    WordApp.Quit '退出程序
    Set WordApp = Nothing '清空
    MsgBox "文件保存在我的文档底下的AAA文件"
    
End Sub

温馨提示:答案为网友推荐,仅供参考
相似回答