Excel 宏 - 遍历同一级别的单元格
所以我想运行 A1-C200 并将所有内容粘贴到 Word 文档中。问题是,我有两种将其粘贴到 Word 中的方法,但每种方法都有其缺点。
目标:将 A1-C200 复制到 Word 中并保留列布局,而不复制空白。
示例 1:
下面的代码将所有内容复制到 Word 中,但从 A1 -> 运行。 A200、B1→ B200、C1→ C200。因为它以这种方式读取我的文件,所以我丢失了我的列布局。我更喜欢这个例子的解决方案,因为这段代码对我来说看起来更清晰。
iMaxRow = 200
" Loop through columns and rows"
For iCol = 1 To 3
For iRow = 1 To iMaxRow
With Worksheets("GreatIdea").Cells(iRow, iCol)
" Check that cell is not empty."
If .Value = "" Then
"Nothing in this cell."
"Do nothing."
Else
" Copy the cell to the destination"
.Copy
appWD.Selection.PasteSpecial
End If
End With
Next iRow
Next iCol
示例 2:
下面的代码复制正确的列布局,但也插入空白。因此,如果填写了 A1-A5 和 A80-A90,我的 Word 文档中将有 75 个空白。
a1 = Range("A1").End(xlDown).Address
lastcell = Range("C1").Address
Range(a1, lastcell).Copy
With Range("A1")
Range(.Cells(1, 1), .End(xlDown).Cells(2, 3)).Copy
End With
Range("A1:C50").Copy
appWD.Selection.PasteSpecial
So I want to run through A1-C200 and paste everything into a Word document. The trouble is, I have two ways of pasting it into Word, but each one has its downfall.
Goal: Copy A1-C200 into Word and keep the column layout, without copying blancs.
Example 1:
The code below copies everything into Word, but runs from A1 -> A200, B1 -> B200, C1 -> C200. Because it reads through my file this way, I lose my column layout. I would prefer a solution for this example, because this code looks clearer to me.
iMaxRow = 200
" Loop through columns and rows"
For iCol = 1 To 3
For iRow = 1 To iMaxRow
With Worksheets("GreatIdea").Cells(iRow, iCol)
" Check that cell is not empty."
If .Value = "" Then
"Nothing in this cell."
"Do nothing."
Else
" Copy the cell to the destination"
.Copy
appWD.Selection.PasteSpecial
End If
End With
Next iRow
Next iCol
Example 2:
The code below copies the correct column layout, but also inserts blancs. So if A1-A5 and A80-A90 are filled in, I will have 75 blancs in my Word document.
a1 = Range("A1").End(xlDown).Address
lastcell = Range("C1").Address
Range(a1, lastcell).Copy
With Range("A1")
Range(.Cells(1, 1), .End(xlDown).Cells(2, 3)).Copy
End With
Range("A1:C50").Copy
appWD.Selection.PasteSpecial
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有多种方法可以做到这一点,不知道哪种方法最快,但这里有一些我快速为您组合在一起的代码。在变体中一次性获取所有范围是从 Excel 中获取数据的最快方法。
There's multiple ways to do this, don't know which is the quickest but here's some code I threw together real quick for you. Getting the range all at once in a variant is the fastest way to grab data out of excel.
不太确定我理解这个问题...但这里有一个刺:
此时 Col1、Col2 和 Col3 包含您的文本,其中包含空白单元格,所以现在循环这些以打印出来
(注意:输入的代码徒手绘制,无需检查...)
not quite sure I understand the prob ... but here's a stab at it:
at this point Col1, Col2, and Col3 contain your text w the blank cells factored out, so now loop over these to print out
(note: code typed in freehand with no checking ... )
将其作为您的第一个解决方案的子项怎么样:
How about this to sub for your first solution: