excel vba:选定的单元格循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21526863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:41:22  来源:igfitidea点击:

excel vba : selected cells loop

vbaexcel-vbaexcel

提问by tgkprog

Would like to iterate each row in a selection in excel VBA.

想在 Excel VBA 中迭代选择中的每一行。

I have:

我有:

Dim rng As Range
Dim s As String
Set rng = Application.Selection
Debug.Print "c :" & rng.Address

This prints

这打印

c :$B$22:$C$29

c :$B$22:$C$29

How to make a loop from row 22 to 29/ parse out the start and end row?

如何从第 22 行到 29 行循环/解析出开始和结束行?

And in separate int variables get the start and end column?

并在单独的 int 变量中获取开始和结束列?

采纳答案by tgkprog

Iterates directly over rows only. I have more than one column selected, wanted outer loop rows only.

仅直接遍历行。我选择了不止一列,只想要外循环行。

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

It doesn't work with non-contiguous selection. Count is incorrect with non-contiguous, you'd have to use For Each cRow In rng.Rows I have not tried this myself, my use case was for a contiguous only. Thank you Danny Holstein (comment in 2019)

它不适用于非连续选择。计数与非连续不正确,您必须在 rng.Rows 中使用 For Each cRow 我自己没有尝试过,我的用例仅用于连续。谢谢 Danny Holstein(2019 年的评论)

回答by dspies

A general solution to looping through a range of cells in Excel:

在 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

Iterates from top-left most cell, across then down.

从最左上角的单元格开始迭代,然后向下迭代。