gpt4 book ai didi

vba - Word VBA Selection.TypeText 和 Selection.InsertParagraph 以错误的顺序插入文本

转载 作者:行者123 更新时间:2023-12-04 22:33:32 28 4
gpt4 key购买 nike

我正在尝试使用 Selection.TypeText 打印 Excel 文件中的某些列功能。
不幸的是,下面的代码首先打印所有结果,然后打印所有段落。我想要结果:

result (tab) result (tab) result (tab) result (tab) result (paragraph)

结果的顺序是正确的,但是宏跳到数据末尾插入一段,然后“跳回来”填写更多数据。
noIntnoData是预先填充并正在工作的两个变量。
For i = 2 To noInt
For k = 2 To noData
If exWb.Sheets("Table1").Cells(k, 1) = exWb.Sheets("Table2").Cells(i, 1) Then
For j = 5 to 9
Selection.TypeText exWb.Sheets("Table1").Cells(k, j) & vbTab
Next j
Selection.InsertParagraph
End If
Next k
Next i

最佳答案

而不是使用 Selection , 使用 Range .然后您可以使用 Range.InsertAfter 可靠地附加文本.以下示例在 Word VBA 中;我无法将它们放在您的 Excel 上下文中,因为我没有所有详细信息。

您的代码的 MCVE(不工作)

Option Explicit
Option Base 0

' A function just to display i, k, and j in a comprehensible manner
Public Function ijk(i As Long, j As Long, k As Long)
ijk = "[I: " & CStr(i) & "; K: " & CStr(k) & "; J: " & CStr(j) & "]"
End Function

Public Sub NotWorking()
Dim noInt As Long
noInt = 3

Dim noData As Long
noData = 4

Dim i As Long, k As Long, j As Long

For i = 2 To noInt
For k = 2 To noData
For j = 5 To 9
Selection.TypeText ijk(i, j, k) & vbTab
Next j
Selection.InsertParagraph
Next k
Next i
End Sub

一个工作版本

更换子 NotWorking上面有这个:
Public Sub Working()
Dim noInt As Long
noInt = 3

Dim noData As Long
noData = 4

Dim i As Long, k As Long, j As Long

' *** Create a Range to refer to wherever the Selection is now
Dim rDest As Range
Set rDest = Selection.Range.Duplicate

For i = 2 To noInt
For k = 2 To noData
For j = 5 To 9
rDest.InsertAfter ijk(i, j, k) & vbTab ' ***
Next j
rDest.InsertAfter Chr(13) ' ***
Next k
Next i
End Sub
Chr(13)是一个段落标记,因此插入它会创建一个新段落。

结果 :

screenshot

关于vba - Word VBA Selection.TypeText 和 Selection.InsertParagraph 以错误的顺序插入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51066145/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com