[英]excel vba : selected cells loop
想在 Excel VBA 中迭代選擇中的每一行。
我有:
Dim rng As Range
Dim s As String
Set rng = Application.Selection
Debug.Print "c :" & rng.Address
這打印
c :$B$22:$C$29
如何從第 22 行到 29 行循環/解析出開始和結束行?
並在單獨的 int 變量中獲取開始和結束列?
在 Excel 中循環遍歷一系列單元格的通用解決方案:
Sub LoopSelection()
Dim cel As Range
Dim selectedRange As Range
Set selectedRange = Application.Selection
For Each cel In selectedRange.Cells
Debug.Print cel.Address, cel.Value
Next cel
End Sub
從最左上角的單元格開始迭代,然后向下迭代。
僅直接遍歷行。 我選擇了不止一列,只想要外循環行。
Option Explicit
'go over selection, merge text in cells, so all in first column in every row.
Sub mergeCombine()
Dim rng As Range
Dim s As String
Set rng = Application.Selection
Debug.Print "c :" & rng.Address
s = rng.Column
Dim cRow As Range
Debug.Print "c :" & rng.Address & "||" & rng.AddressLocal
Dim ir, ic As Integer
For ir = 1 To rng.Rows.Count
Set cRow = rng.Rows(ir)
s = ""
For ic = 1 To rng.Columns.Count
s = s & cRow.Columns(ic).Text
Cells(cRow.Row, cRow.Columns(ic).Column).Formula = ""
If (ic + 1) <= rng.Columns.Count Then
s = s & " "
End If
Next
Cells(cRow.Row, cRow.Column).Formula = ""
Cells(cRow.Row, cRow.Column).Formula = s
Next
End Sub
它不適用於非連續選擇。 計數與非連續不正確,您必須在 rng.Rows 中使用 For Each cRow 我自己沒有嘗試過,我的用例僅用於連續。 謝謝 Danny Holstein(2019 年的評論)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.