wordApp.Selection.Fields.Add wordApp.Selection.Range, wdFieldEmpty, "SEQNUMBER", True提示运行时错误“4608”:数值超出范围,注意这是在excel中运行的代码,但是需要在输出的word中实现功能
时间: 2024-03-01 15:50:02 浏览: 29
抱歉,我之前的回答有误。在excel中运行的代码确实可以向word中输出文本,但是却不能直接使用word中的常量值。正确的做法是,在excel中声明常量,并将其赋值为对应的常量值,如下所示:
```
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")
Set wordDoc = wordApp.Documents.Add
wordApp.Visible = True
j = 0
For i = 2 To 100
If excelSheet.Cells(i, 3).Value = "Y" Then
j = j + 1
Set excelRange = excelSheet.Cells(i, 2)
wordApp.Selection.TypeText "Seq "
wordApp.Selection.Fields.Add wordApp.Selection.Range, wdFieldEmpty, "SEQNUMBER", True
wordApp.Selection.TypeText "(XTH)"
wordApp.Selection.TypeText excelRange.Value
wordApp.Selection.TypeParagraph
End If
Next i
Set wordDoc = Nothing
Set wordApp = Nothing
Set excelRange = Nothing
Set excelSheet = Nothing
Application.DisplayAlerts = True
```
在这个示例中,我将常量值的声明放在了代码的最上面,同时用Const语句将常量赋值为对应的值。这样,在代码中就可以直接使用这些常量了。请注意,这里的常量值与Word中的常量值是一致的,因此可以正确地插入seq域代码。