繁体   English   中英

从Excel VBA创建和格式化Word表时遇到麻烦

[英]Having troubles creating and formatting Word tables from Excel VBA

我是MS Word VBA的新手,在使用Excel操作Word文档时遇到了麻烦。

到目前为止最大的问题是:在Word VBA中工作的代码在Excel中不起作用。 非常奇怪和令人沮丧。

以下是代码:

Sub abc()
Dim MSWordApp As Object, MSWordDoc As Object

    Set MSWordApp = CreateObject("Word.Application")
    Set MSWordDoc = MSWordApp.Documents.Add
    MSWordApp.Visible = True
    With MSWordDoc
        With .PageSetup
            .TopMargin = Application.CentimetersToPoints(0.51)
            .BottomMargin = Application.CentimetersToPoints(0.51)
            .LeftMargin = Application.CentimetersToPoints(0.51)
            .RightMargin = Application.CentimetersToPoints(0.51)
        End With
        .Tables.Add Range:=.Range(0, 0), NumRows:=3, NumColumns:=2
        With .Tables(1)
            .Rows.Alignment = wdAlignRowCenter
            .Rows.HeightRule = wdRowHeightExactly
            .Rows.Height = Application.CentimetersToPoints(9.55)
            .Columns.PreferredWidthType = wdPreferredWidthPoints
            .Columns.PreferredWidth = Application.CentimetersToPoints(9.9)
        End With
    End With

    MSWordApp.Activate
    Set MSWordApp = Nothing
    Set MSWordDoc = Nothing
End Sub

这些代码在MS Word中完美运行(当我在MS Word中使用它们时,我已经更改了对象的名称等)。

但是,在Excel中发生了奇怪的事情:

1)“。Row.Alignment = wdAlignRowCenter”根本不起作用。 Word表的Rows.Alignment保持默认状态。

2)“。Column.PreferredWidthType = wdPreferredWidthPoints”在Excel中导致错误。 它在Word中工作正常; 虽然在Excel中,每次调用此属性时都会弹出一个空错误消息。 不知道为什么......

从Excel VBA控制Microsoft Word时,需要添加对Microsoft Word对象库的引用。 为此,请确保您在VBA窗口中的模块上,然后单击Tools ,然后单击References... 在弹出窗口中,向下滚动以查找“Microsoft Word XX.X对象库”。 版本#将根据您安装的内容而有所不同。

添加对Word对象库的引用

如果它没有显示在列表中,您可以在硬盘上找到它,方法是单击“浏览...”并导航到安装了MS Word的程序文件文件夹,然后选择名为“MSWORD.OLB”的文件。 。

由于您的代码是为了使用后期绑定而编写的,因此您不应该添加对Word的引用。 相反,您需要定义或替换您正在使用的Word常量。 例如,而不是:

.Rows.Alignment = wdAlignRowCenter
.Rows.HeightRule = wdRowHeightExactly

你可以使用:

.Rows.Alignment = 1  '1=wdAlignRowCenter
.Rows.HeightRule = 2 '2=wdRowHeightExactly

或者,之后:

Dim MSWordApp As Object, MSWordDoc As Object

你会插入:

Const wdAlignRowCenter as Long = 1: Const wdRowHeightExactly as Long = 2

否则,如果您要设置对Word的引用,则应使您的代码始终与早期绑定保持一致。 例如,而不是:

Dim MSWordApp As Object, MSWordDoc As Object

    Set MSWordApp = CreateObject("Word.Application")
    Set MSWordDoc = MSWordApp.Documents.Add

你可能会用:

Dim MSWordApp As New Word.Application, MSWordDoc As Word.Document

    Set MSWordDoc = MSWordApp.Documents.Add

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM