[英]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中,每次调用此属性时都会弹出一个空错误消息。 不知道为什么......
由于您的代码是为了使用后期绑定而编写的,因此您不应该添加对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.