[英]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.