Word VBA(批量复制Excel表格和Word表格到Word中)

Function Test()  '使用双字典
    
    SearchPath = FolderDialog("请选择文件夹")
    If SearchPath = "" Then
        Exit Function
    End If
    WordName = SplitPath(CStr(SearchPath), 1)
    
    
    Dim sFile As Object, fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    Set logFile = fso.CreateTextFile(SearchPath & WordName & "日志.txt", True)
    
    Dim MyWord As Word.Application
    Set MyWord = New Word.Application
    
    MyWord.Application.ScreenUpdating = False
    MyWord.Application.Visible = True
    MyWord.Application.DisplayAlerts = wdAlertsNone
    
    Set myDoc = MyWord.Documents.Add
    With MyWord.ActiveDocument.PageSetup
        .Orientation = wdOrientLandscape '纸张方向横向
    End With
    
    
    
    Dim CGType() As String '动态数组
    ReDim Preserve CGType(7)
    CGType(0) = "控制点"
    CGType(1) = "界址点"
    CGType(2) = "界址边长"
    CGType(3) = "房角点"
    CGType(4) = "房屋边长"
    CGType(5) = "房屋面积"
    CGType(6) = "巡查"
    
    
    Dim ExcelApp As Object
    If Tasks.Exists("Microsoft Excel") = True Then Tasks("Microsoft Excel").Close
    Set ExcelApp = CreateObject("Excel.Application")
    Dim wkBook As Object   '代表excelworkbook(也就是excel工作簿文件 .xls  .xlsx)
    Dim wkSheet As Object  '代表excel的工作页
    ExcelApp.Application.EnableEvents = False '禁止宏等提示的运行
    ExcelApp.Application.DisplayAlerts = False
    ExcelApp.Application.CutCopyMode = False
    
    
    Dim DicList, FileList, CunDic, I, FileName(), FilePath()
    Dim excelPath As String
    Set DicList = CreateObject("Scripting.Dictionary")
    Set FileList = CreateObject("Scripting.Dictionary")
    
    DicList.Add SearchPath, ""  '初始化目录
    
    '**************遍历一级目录 获取路径和村名*******************
    
    Do While I < DicList.Count
        Key = DicList.keys '本次要遍历的目录
        NowDic = Dir(Key(I), vbDirectory) '开始查找
        Do While NowDic <> ""
            If (NowDic <> ".") And (NowDic <> "..") Then
                If (GetAttr(Key(I) & NowDic) And vbDirectory) = vbDirectory Then '找到子目录,则添加
                    If Not DicList.Exists(Key(I) & NowDic & "\") Then
                        DicList.Add Key(I) & NowDic & "\", NowDic
                    End If
                End If
            End If
            NowDic = Dir() '再找
        Loop
        Exit Do
        
    Loop
    '****************************************************
    
    
    '********************获取村所对应的文件夹和子文件夹********************************
    Set CunDic = CreateObject("Scripting.Dictionary")
    k = DicList.keys
    v = DicList.Items
    For I = 0 To DicList.Count - 1
        If Not v(I) = "" Then
            CunMin = v(I)
            '加入村名 放在文件字典里
            If Not FileList.Exists(CunMin) Then
                FileList.Add CunMin, ""
            End If
            'FileList.RemoveAll
            '*********************遍历村名下所有的文件夹*****************************
            CunDic.RemoveAll
            CunDic.Add k(I), ""
            J = 0
            Do While J < CunDic.Count
                Key = CunDic.keys '本次要遍历的目录
                NowDic = Dir(Key(J), vbDirectory)
                Do While NowDic <> ""
                    If (NowDic <> ".") And (NowDic <> "..") Then
                        If (GetAttr(Key(J) & NowDic) And vbDirectory) = vbDirectory Then '找到子目录,则添加
                            If Not CunDic.Exists(Key(J) & NowDic & "\") Then
                                CunDic.Add Key(J) & NowDic & "\", ""
                            End If
                        End If
                    End If
                    NowDic = Dir() '再找
                Loop
                J = J + 1
            Loop
            '***************************************************
            
            '******************************在村名下对应的所有目录下搜索XLS文件*******************************
            
            For Each Key In CunDic.keys '查找所有目录中的控制点文件
                
                For m = 0 To UBound(CGType) - 1
                    If m <= UBound(CGType) - 2 Then
                        NowFile = Dir(Key & "*" & CGType(m) & "*.xls")
                    Else
                        NowFile = Dir(Key & "*" & CGType(m) & "*.docx")
                    End If
                    Do While NowFile <> ""
                        If Not FileList.Exists(CunMin) Then
                            FileList.Add CunMin, Key & NowFile 'FileList.Key=文件名,FileList.Item=目录
                        Else
                            If FileList.Item(CunMin) = "" Then
                                FileList(CunMin) = Key & NowFile
                            Else
                                FileList.Item(CunMin) = FileList.Item(CunMin) & "@" & Key & NowFile
                            End If
                        End If
                        NowFile = Dir()
                    Loop
                Next
            Next
        End If
    Next
    '*********************************************************************************************
    FileName() = FileList.keys
    FilePath() = FileList.Items
    
    
    For m = 0 To FileList.Count - 1
        
        element = FileName(m)
        excelPathArray = Split(FileList(element), "@")
        '**********记录日志  7文件是否缺少文件******************************
        For x = 0 To UBound(CGType) - 1
            boolFind = False
            For y = 0 To UBound(excelPathArray)
                excelPath = excelPathArray(y)
                If InStr(excelPath, CGType(x)) > 0 Then
                    boolFind = True
                    Exit For
                End If
            Next
            If Not boolFind Then
                logFile.WriteLine (element & "缺少" & CGType(x) & "成果")
            End If
        Next
        
        '************************************************************************
        For n = 0 To UBound(excelPathArray)
            excelPath = excelPathArray(n)
            extention = SplitPath(excelPath, 2)
            If StrComp(extention, "xls", vbTextCompare) = 0 Then
                
                Set wkBook = ExcelApp.Workbooks.Open(excelPath)
                Set wkSheet = wkBook.Worksheets(1)
                lastRowCount = ExcelApp.ActiveSheet.UsedRange.Rows.Count
                lastColumnCount = ExcelApp.ActiveSheet.UsedRange.Columns.Count
                lastEnColumnCount = ChgNumToABC(lastColumnCount)
                
                excelrowcolumn = lastEnColumnCount & CStr(lastRowCount)
                'Dim rng As Object
                'Set rng = wkSheet.Range("A1:" & excelrowcolumn)
                'rn.Copy
                MyWord.Activate
                
                With MyWord
                    If n = 0 Then
                        MyWord.Application.Selection.InsertBefore Text:=element
                        MyWord.Application.Selection.ParagraphFormat.OutlineLevel = wdOutlineLevel1
                        MyWord.Application.Selection.EndKey Unit:=wdLine, Extend:=wdMove
                    End If
                    wkSheet.Range("A1:" & excelrowcolumn).Copy
                    'myDoc.Paragraphs(1).Range.PasteExcelTable False, False, False  '粘贴为表格
                    
                    MyWord.Application.Selection.PasteExcelTable False, False, False
                    MyWord.Application.Selection.ParagraphFormat.OutlineLevel = wdOutlineLevelBodyText
                    If n <= UBound(excelPathArray) - 1 Then
                        MyWord.Application.Selection.EndKey Unit:=wdStory, Extend:=wdMove
                        MyWord.Application.Selection.Range.InsertAfter (vbCrLf)
                        'Else
                        'MyWord.Application.Selection.EndKey Unit:=wdStory, Extend:=wdMove
                    End If
                    ExcelApp.Application.Workbooks.Close
                End With
                'Set MyWord = Nothing
            ElseIf StrComp(extention, "docx", vbTextCompare) = 0 Then
                MyWord.Activate
                Set otherDoc = MyWord.Documents.Open(excelPath)
                otherDoc.Activate
                MyWord.Application.Selection.WholeStory
                MyWord.Application.Selection.Copy
                myDoc.Activate
                MyWord.Application.Selection.EndKey Unit:=wdLine, Extend:=wdMove
               
                MyWord.Application.Selection.Paste
                MyWord.Application.Selection.InsertBreak (wdPageBreak)
                otherDoc.Close
            End If
        Next
    Next
    
    '*************************设置表格居中而非内容居中*************************
    For Each tb In myDoc.Tables
    tb.Rows.Alignment = wdAlignRowCenter
    Next
    '************************************************
    MyWord.ActiveDocument.SaveAs FileName:=CStr(SearchPath) & WordName & ".doc"
    MyWord.ActiveDocument.Close
    MyWord.Application.ScreenUpdating = Ture
    MyWord.Quit SaveChanges:=wdDoNotSaveChanges
    ExcelApp.Application.CutCopyMode = False
    logFile.Close
    Set logFile = Nothing
    Set fso = Nothing
    ExcelApp.Application.Quit
    Set CunDic = Nothing
    Set FileList = Nothing
    Set DicList = Nothing
    Set DicList = Nothing
    Set MyWord = Nothing
    
    MsgBox "Done"
    
End Function


'ResultFlag=0 获取路径  'ResultFlag=1 获取文件名     'ResultFlag=2 获取扩展名
Public Function SplitPath(FullPath As String, ResultFlag As Integer) As String
    Dim SplitPos As Integer, DotPos As Integer
    SplitPos = InStrRev(FullPath, "\")
    DotPos = InStrRev(FullPath, ".")
    Select Case ResultFlag
        Case 0
            SplitPath = Left(FullPath, SplitPos - 1)
        Case 1
            If DotPos = 0 Then
                If Right(FullPath, 1) = "\" Then
                    FullPath = Left(FullPath, Len(FullPath) - 1)
                    SplitPos = InStrRev(FullPath, "\")
                End If
                DotPos = Len(FullPath) + 1
            End If
            SplitPath = Mid(FullPath, SplitPos + 1, DotPos - SplitPos - 1)
        Case 2
            If DotPos = 0 Then DotPos = Len(FullPath)
            SplitPath = Mid(FullPath, DotPos + 1)
        Case Else
            Err.Raise vbObjectError + 1, "SplitPath Function", "无效参数!"
    End Select
End Function




Function FolderDialog(strTitle As String) As String    '获取选择文件夹对话框的目录
    Set objShell = CreateObject("Shell.Application")
    Set objDialog = objShell.BrowseForFolder(0, strTitle, 0, 0)
    If Not objDialog Is Nothing Then
        If Right(objDialog.self.Path, 1) = "\\" Then
            FolderDialog = objDialog.self.Path
        Else
            FolderDialog = objDialog.self.Path & "\"
        End If
    Else
        FolderDialog = ""
        MsgBox "没有选择文件夹"
    End If
    Set objDialog = Nothing
    Set objShell = Nothing
End Function


'*****************************************************************************
'将Excel中列数转换为列名(如27列--->AA列)
'参数:var 列数
'返回:列名 string
'*****************************************************************************
Public Function ChgNumToABC(ByVal var As Integer) As String
    Dim res As String
    Dim remainder As Integer '余数
    Dim quotient As Integer '商
    
    remainder = var Mod 26
    
    If remainder = 0 Then
        var = var - 26
        remainder = 26
    End If
    quotient = var \ 26
    If quotient <> 0 Then
        res = ChgNumToABC(quotient)
    End If
    ChgNumToABC = res & Chr(remainder + 65 - 1)
End Function


Function zhzm(num As Long) As String
    Dim inum As Long
    Dim imod As Long
    Application.Volatile
    Do While num
        inum = IIf(num Mod 26 = 0, num \ 26 - 1, num \ 26)
        imod = IIf(num Mod 26 = 0, 26, num Mod 26)
        zhzm = Chr(64 + imod) & zhzm
        num = inum
    Loop
End Function



  • 10
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sub ExtractExcelDataToWord() ' 声明变量 Dim excelFilePath As String Dim wordFilePath As String Dim wordApp As Object Dim wordDoc As Object Dim excelApp As Object Dim excelWorkbook As Object Dim excelWorksheet As Object Dim tableRange As Object Dim tableData As Variant Dim i As Integer Dim j As Integer Dim rowCount As Integer Dim columnCount As Integer ' 设置文件路径 excelFilePath = "D:\data.xlsx" wordFilePath = "D:\output.docx" ' 创建Word应用程序 Set wordApp = CreateObject("Word.Application") ' 打开Word文档 Set wordDoc = wordApp.Documents.Open(wordFilePath) ' 创建Excel应用程序 Set excelApp = CreateObject("Excel.Application") ' 打开Excel工作簿 Set excelWorkbook = excelApp.Workbooks.Open(excelFilePath) ' 指定工作表 Set excelWorksheet = excelWorkbook.Worksheets(1) ' 获取表格区域 Set tableRange = excelWorksheet.UsedRange ' 获取表格数据 tableData = tableRange.Value ' 获取表格行数和列数 rowCount = UBound(tableData, 1) columnCount = UBound(tableData, 2) ' 在Word文档创建表格 wordDoc.Tables.Add Range:=wordDoc.Range(0, 0), NumRows:=rowCount, NumColumns:=columnCount ' 将表格数据添加到Word表格 For i = 1 To rowCount For j = 1 To columnCount wordDoc.Tables(1).Cell(i, j).Range.Text = tableData(i, j) Next j Next i ' 保存Word文档 wordDoc.Save ' 关闭Word文档和应用程序 wordDoc.Close wordApp.Quit ' 关闭Excel工作簿和应用程序 excelWorkbook.Close excelApp.Quit ' 释放对象 Set wordDoc = Nothing Set wordApp = Nothing Set excelWorksheet = Nothing Set excelWorkbook = Nothing Set excelApp = Nothing ' 提示完成 MsgBox "数据已提取到Word文档。" End Sub

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值