[英]How do I loop through cells and create a new row if it contains a specific string in vba?
[英]How do I loop through the cells in a Row to add to a string?
我正在尝试在Excel中编写宏以格式化和复制当前选择。 作为此过程的一部分,我想遍历所有单元以有条件地对其行进行格式化(第一行略有不同)。 对我而言,最有意义的是“ Rows()”,但它在For Each循环中返回不匹配错误。 有什么想法我可以解决这个问题吗? (此外,它应该根据选择将行数作为变量使用,现在我只用1-4进行尝试。)
Sub Convert()
Dim sOutput As String
Dim rSelection As Range
Dim rCell As Range
Dim rHead As Range
Set rSelection = Selection.Cells
Set rHead = rSelection.Rows(1)
sOutput = "||"
For Each rCell In rHead
sOutput = sOutput & rCell.Value & "||"
Next rCell
sOutput = sOutput & Chr(10) & "|"
For Each rCell In rSelection.Rows(2)
sOutput = sOutput & rCell.Value & "|"
Next rCell
'sOutput = sOutput & Chr(10) & "|"
For Each rCell In rSelection.Rows(3)
sOutput = sOutput & rCell.Value & "|"
Next rCell
'sOutput = sOutput & Chr(10) & "|"
For Each rCell In rSelection.Rows(4)
sOutput = sOutput & rCell.Value & "|"
Next rCell
fCopy (sOutput)
MsgBox "Table has been copied and formatted."
End Sub
谢谢!
使用Range
变量类型并遍历所有IterateRange.Rows属性,其中IterateRange
是您要遍历每一行的任何范围。
Private Sub rowTester()
Dim mRow As Range
For Each mRow In Range("A1:B4").Rows
Debug.Print mRow.Row
'your code here which will execute on each row in the above range
Next mRow
End Sub
说“选择”是工作表中某处的任意矩形范围。 我们要创建另一个仅是该范围第三行的范围:
Sub TheThirdRow()
Dim r As Range, rThirdRow As Range
Set r = Selection
Set rThirdRow = Intersect(r(3, 1).EntireRow, r)
rThirdRow.Select
End Sub
您可以循环遍历rThirdRow等单元格
第二行或第四行等类似。
将rSelection.Rows(2)
更改为rSelection.Rows(2).Cells
以修复您rSelection.Rows(2).Cells
的错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.