【问题标题】:Displaying merged cell data in a For loop在 For 循环中显示合并的单元格数据
【发布时间】:2019-02-21 23:22:57
【问题描述】:

我正在尝试使用 VBA 在 Excel 中的 For 循环中显示合并单元格的内容。

我有一个包含非常简单数据的工作表

这是我的代码:

'finding last record in my initial list    
sheet_last_row = Sheets("mylist").Range("A" & Rows.Count).End(xlUp).Row

For i = 2 To sheet_last_row
    last_row = Sheets("results").Cells(Rows.Count, 1).End(xlUp).Row

    If Sheets("mylist").Cells(i, 1).Value = 2 Then
        'test if cell is merged
        If Sheets("mylist").Cells(i, 2).MergeCells Then
            RowCount = Sheets("mylist").Cells(i, 2).Value
        End If
        Sheets("mylist").Cells(i, 1).EntireRow.Copy Sheets("results").Cells(last_row + 1, 1)
    End If
Next i

我通过这段代码得到以下结果;

我是新手。谁能告诉我如何完成这项工作。

【问题讨论】:

  • 你能贴一张想要的结果的图片吗?
  • 仅供参考 - 在大多数情况下,出于类似的原因合并单元格被认为是不好的做法,等等。我会重新考虑您是否真的需要首先合并单元格。
  • 这个 RowCount 变量有什么用?你究竟想用 MergeCells 做什么?顺便说一句,单元格 Sarah 所在的单元格实际上是单元格 B5,因此如果您循环遍历范围并跳过空单元格(范围 B6:B9 被“视为”为空),您将获得正确的结果。我不认为这很容易,所以你必须更好地解释遇到合并单元格时该怎么做。

标签: excel vba for-loop


【解决方案1】:

你可以试试:

Option Explicit

Sub test()

    Dim LastRowA As Long, LastRowB, LastRowC As Long, LastRowE As Long, MaxRow As Long
    Dim cell As Range, rng As Range

    With ThisWorkbook.Worksheets("Sheet1")

        'Find the lastrow for all the available columns
        LastRowA = .Cells(.Rows.Count, "A").End(xlUp).Row
        LastRowB = .Cells(.Rows.Count, "B").End(xlUp).Row
        LastRowC = .Cells(.Rows.Count, "C").End(xlUp).Row

        'Get the longer last row in order to avoid losing data if the last cell of a column is merge or empty
        MaxRow = WorksheetFunction.Max(LastRowA, LastRowB, LastRowC)

        'Set the area to loop
        Set rng = .Range("A2:C" & MaxRow)

        'Start looping
        For Each cell In rng

            'If the cell is merger
            If cell.MergeCells Then

                'Find the last row of column E
                LastRowE = .Cells(.Rows.Count, "E").End(xlUp).Row

                'Paste cell value in column E
                .Range("E" & LastRowE + 1).Value = cell.Value
                'Paste cell address in column F
                .Range("F" & LastRowE + 1).Value = cell.Address

            End If

        Next

    End With

End Sub

结果:

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 2017-09-28
    • 2023-03-28
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    相关资源
    最近更新 更多