从Excel绘制表格到Word书签

rakesh seebaruth

将表格从Excel插入到Word中,按行和列填充表格。Vba在.draw中打开我的文件,然后在Word文档中填写表格。我遇到的主要问题是,尽管我在Word文档中插入了书签,但表格并未插入该书签的位置。我的代码如下:

Sub CreateTableInWord()

    Dim objWord As Object, objDoc As Object, objTbl As Object, objRow As Object
    Dim objCol As Object, colSets As Long, numMonths As Long, i As Long, n As Long, c As Long
    Dim amt, dtStart, tblRows As Long, tblCols As Long, rw As Long, col As Long

    numMonths = Range("A1").Value
    amt = Range("B1").Value
    dtStart = Range("C1").Value
    colSets = Range("D1").Value 'how many sets of columns ?

    tblRows = 1 + Application.Ceiling(numMonths / colSets, 1) 'how many table rows?
    tblCols = colSets * 3                                     'how many table cols?

    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    'Set objDoc = objWord.Documents.Add
     Set objDoc = objWord.Documents.Open("C:\Users\rakesh\Desktop\mailmerge\lease2.docx")

    Dim oRange As Object
    Set oRange = objDoc.Bookmarks("RS").Range

    Set objTbl = objDoc.Tables.Add(Range:=objDoc.Paragraphs(1).Range, _
                 NumRows:=tblRows, NumColumns:=tblCols)

    c = 0
    For n = 1 To colSets
        objTbl.Cell(1, c + 1).Range.Text = "Instal No"
        objTbl.Cell(1, c + 1).Range.Bold = True
        objTbl.Cell(1, c + 2).Range.Text = "Amt(Rs)"
        objTbl.Cell(1, c + 2).Range.Bold = True
        objTbl.Cell(1, c + 3).Range.Text = "Due Date"
        objTbl.Cell(1, c + 3).Range.Bold = True
        c = c + 3
    Next n
    objTbl.Range.ParagraphFormat.Alignment = 1 ' wdAlignParagraphCenter

    rw = 2
    col = 0
    For i = 1 To numMonths

        'rw = 1 + Application.Ceiling(i / colSets, 1)  'fill across and then down
        rw = IIf(i Mod (tblRows - 1) = 1, 2, rw + 1)   'fill down then across

        objTbl.Cell(rw, col + 1).Range.Text = i
        objTbl.Cell(rw, col + 2).Range.Text = amt
        objTbl.Cell(rw, col + 3).Range.Text = Format(DateAdd("m", i - 1, dtStart), "dd/mm/yyyy")



        'col = IIf(i Mod colSets = 0, 0, col + 3)         'fill across and then down
        col = IIf(i Mod (tblRows - 1) = 0, col + 3, col) 'fill down and then across

    Next i

End Sub
巨足动物

«如何自动调整表格的列宽,我尝试了objTbl.Range.EntireColumn.AutoFit,但我无法正常运行»

Word不是Excel!Word没有EntireColumn这样的表属性。您确实应该花一些时间来学习Word的属性和方法。尝试:

With objDoc
  Set objTbl = .Tables.Add(Range:=.Bookmarks("RS").Range, _
    NumRows:=tblRows, NumColumns:=tblCols, _
    DefaultTableBehavior:=wdWord9TableBehavior, _
    AutofitBehaviour:=wdAutoFitContent)
End With

要么:

objTbl.Columns.AutoFit

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章