将Word表复制到Excel并按表格式设置

问题描述 投票:1回答:1

我在Word VBA中有一个宏,该宏可从Word文件复制表格并将其粘贴到Excel。

它像这样粘贴:enter image description here

我现在的问题是,是否有可能将表格式化为“ Excel表”,就像在Word中使用VBA在excel中插入表一样?

要获得最终结果,如下所示:enter image description here

我的意思是我知道如何使用同一Excel文件中的宏来执行此操作,但如何从单词vba格式化它?

我的问题是我需要从vba单词开始操作,因为我无法选择在excel vba中执行此操作。

谢谢大家!

我的代码是:

    Dim wrdTbl As Table, c As Long
    'Excel Objects
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object

    'Set your table
    With ActiveDocument
        If ActiveDocument.Tables.Count >= 1 Then
            Set wrdTbl = .Tables(InputBox("Table # to copy? There are " & .Tables.Count & " tables to choose from."))
        End If
    End With
    'Create a new Excel Application
    Set oXLApp = CreateObject("Excel.Application")
    With oXLApp
    'Hide Excel
        .Visible = False
        'Open the relevant Excel file
        Set oXLwb = oXLApp.Workbooks.Open("C:\Users\" & Environ("Username") & "\Desktop\ExcelEx.xlsx")
    End With
    wrdTbl.Range.Copy
    With oXLwb.Sheets(1)
        .Paste .Range("A1")
    End With
    'Close and save Excel file
    oXLwb.Close True
    'Cleanup (VERY IMPORTANT)
    oXLApp.Quit
    Set oXLwb = Nothing: Set oXLApp = Nothing
    MsgBox "Done"
End Sub
vba ms-word copy-paste word-table
1个回答
2
投票

类似的东西

With oXLwb.Sheets(1)
    .Paste .Range("A1")
    Dim LastRow As Long
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    Dim LastCol As Long
    LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

    .ListObjects.Add(SourceType:=xlSrcRange, Source:=.Range("A1", .Cells(LastRow, LastCol)), XlListObjectHasHeaders:=xlYes).TableStyle = "TableStyleMedium2"
End With

应将其格式化为表格。调整以适应您的需求和所需的样式。

关于如何Find last row, column or last cell,这是一个很好的资源。

© www.soinside.com 2019 - 2024. All rights reserved.