wordApp.Selection.Fields.Add Range:=wordApp.Selection.Range, Type:=wdFieldEmpty, Text:="SEQNUMBER", PreserveFormatting:=True依然提示运行时错误“4608”:数值超出范围,注意,这是在excel中运行的vba代码,但是需要在word中实现功能
时间: 2024-03-01 21:50:27 浏览: 211
matlab零基础入门彩色图像技术:25 matlab与word的交互.zip
我猜测可能是因为 Word 对象库未正确加载导致的。您可以尝试在 VBA 中打开 Word 文档,然后再执行插入 SEQNUMBER 字段的操作。示例代码如下:
```
Sub ExportToWord()
Const wdFieldEmpty As Integer = 0
Const wdGoToBookmark As Integer = -1
Const wdCollapseEnd As Integer = 0
Dim wordApp As Object
Dim wordDoc As Object
Dim excelSheet As Worksheet
Dim excelRange As Range
Dim i As Integer, j As Integer
Application.DisplayAlerts = False
Set excelSheet = ActiveSheet
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = True
Set wordDoc = wordApp.Documents.Add
' 打开 Word 文档后再执行以下操作
wordDoc.Activate
j = 0
For i = 2 To 100
If excelSheet.Cells(i, 3).Value = "Y" Then
j = j + 1
' 插入 SEQNUMBER 字段
wordApp.Selection.Fields.Add Range:=wordApp.Selection.Range, Type:=wdFieldEmpty, Text:="SEQNUMBER", PreserveFormatting:=True
' 插入文本
Set excelRange = excelSheet.Cells(i, 2)
wordApp.Selection.TypeText "Seq "
wordApp.Selection.TypeText "(XTH)"
wordApp.Selection.TypeText excelRange.Value
wordApp.Selection.TypeParagraph
End If
Next i
wordApp.Selection.EndKey 6
Set wordDoc = Nothing
Set wordApp = Nothing
Set excelRange = Nothing
Set excelSheet = Nothing
Application.DisplayAlerts = True
End Sub
```
这样,您的代码应该就可以在 Word 中插入 SEQNUMBER 字段了。
阅读全文