excel - 将多个值写入一个单元格 - VBA

标签 excel vba loops concatenation is-empty

我对 VBA 非常陌生,正在尝试确定如何在一个单元格中存储多个值。例如,我首先:

  1. 扫描一行中的每个单元格以确定其是否为空白。 (A2:F3)
  2. 然后我确定了该空白单元格的列标题。 (A1:F1)
  3. 我创建了一个消息框,其中显示单元格和相应列标题的标题。 (单元格为空。列标题为状态。)

我需要一些帮助来弄清楚:

  1. 如何循环,以便每个列标题在保存到 G 列时不会覆盖下一个列标题。
  2. 如何循环和连接以使一行中的多个列标题位于同一单元格中。 (例如,姓名、学校、州 - 这些将是我拉入最后一列的标题。)

感谢您提供的任何帮助!

Sub EmptyCells()

Dim Cell As Range
Dim lrow As Long, i As Integer
Dim lcol As Long
Dim rw As Range
Dim reString As String
Dim ResultRng As Range


    'Find the last non-blank cell in Column "School"
    lrow = Cells(Rows.Count, 3).End(xlUp).Row
    lcol = Cells(1, Columns.Count).End(xlToLeft).Column

    MsgBox "Last Row: " & lrow


   Set ResultRng = Range("G2:G3")

For Each rw In Sheets(1).Range("A1:F3").Rows
    For Each Cell In rw.Cells
        If IsEmpty(Cell.Value) Then
            'MsgBox Cell.Address & " is empty. " & "The cell row number is " & Cell.Row & "." & vbNewLine & "The column header is " & Cell.Offset((1 - Cell.Row), 0)

            ResultRng = Cell.Offset((1 - Cell.Row), 0)

        End If
    Next

Next

MsgBox "Complete"

End Sub

最佳答案

我在这里更广泛地使用了您的 lrow 和 lcol。

Sub EmptyCells()
    Dim lrow As Long, lcol As Long
    Dim i As Integer, r As Long, c As Long
    Dim reString As String

    With Worksheets("sheet1")
        'Find the last non-blank cell in Column "School"
        lrow = .Cells(.Rows.Count, 3).End(xlUp).Row
        lcol = .Cells(1, .Columns.Count).End(xlToLeft).Column

        MsgBox "Last Row: " & lrow

        For r = 2 To lrow
            reString = vbnullstring
            For c = 1 To lcol
                If IsEmpty(.Cells(r, c)) Then
                    'MsgBox .Cells(r, c).Address(0,0) & " is empty. " & _
                            "The cell row number is " & r & "." & vblf & _
                            "The column header is " & .Cells(1, c).value
                    reString = reString & ", " & .Cells(1, c).Value
                End If
            Next c
            .Cells(r, c) = Mid(reString, 3)
        Next r
    End With

    MsgBox "Complete"

End Sub

关于excel - 将多个值写入一个单元格 - VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50781209/

相关文章:

excel - 使用 Excel 数据透视表或 Power Pivot 将多个变量转换为值

java - 如何将变量设置为 Apache POI 迭代数据值

sql - 无法在 Excel 中查询名称中带有空格的工作表上的命名范围

c - 凯撒密码中最后一个字母后循环回到字母表开头的逻辑

excel - Excel 数据透视表中的最大值总和

excel - 如何阻止excel更改单元格内的公式?

vba - 当子表单绑定(bind)到表时,是否可以在子表单的表单上引发事件?

VBA - 在子程序中设置属性以在调试时自动跳过

在 C 中使用 while 循环的复合条件。

java - 循环多次打印最后一行 - 我做错了什么? - 使用BufferedReader