【发布时间】:2019-06-20 08:22:27
【问题描述】:
我是 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) ".Rows.Alignment = wdAlignRowCenter" 根本不起作用。 Word 表的 Rows.Alignment 保持默认。
2) ".Columns.PreferredWidthType = wdPreferredWidthPoints" 导致 Excel 出错。它在 Word 中运行良好;虽然在 Excel 中,每次调用此属性时都会弹出一个空的错误消息。不知道为什么...
【问题讨论】:
-
您是否在 excel VBA 模块中添加了对 Word VBA 库的引用?
-
@Greg Viers ...上帝。你说的正是原因。愚蠢的新手错误
-
我会为其他出现的新手提交正确的答案。 :)