首页 > 解决方案 > 组合单元格的 Excel VBA 问题

问题描述

我正在编写一个 Excel VBA 程序来生成文本。我正在使用 IF 语句来确定某个特定文本是否在单元格中,并根据该文本连接一个字符串。

我对组合单元格有疑问:

在此处输入图像描述

IF Cells(1,1) Like "A" and Cells(1,2) Like "---" Then
concatenate something
end if

以上作品

IF Cells(2,1) Like "B" and Cells(2,2) Like "---" Then
concatenate something
end if

这不起作用,因为根据 MsgBox (Cells(2, 2).Value) 而不是“---”,Cell(2,2) 是空的。

是否可以让代码正常工作,而无需再次拆分单元格?

我想逐行连接文本,VBA代码应该将“B”右侧的单元格值识别为“---”。

标签: excelvba

解决方案


Cells(1,1).Value是“A”。 Cells(1,2).Value是 ” - -”。
Cells(2,1).Value是空的。 Cells(3,2).Value是空的。
Cells(3,1).Value为B”。 Cells(3,2).Value是空的。

仅仅因为您合并了上面的单元格,并不会改变单元格在第 3 行中。只有合并范围中的左上角单元格有值。(虽然,有办法 解决这个问题。)

您可以使用Range.MergeCells.检查单元格是否合并。您可以使用获得合并单元格的值Range.MergeArea

例如:
Cells(1,1).MergeArea.Cells(1,1)是“A”。 Cells(2,2).MergeArea.Cells(1,1)是 ” - -”。 Cells(1,1).MergeCellsTrue
Cells(2,1).MergeArea.Cells(1,1)是“A”。 Cells(2,2).MergeArea.Cells(1,1)是 ” - -”。 Cells(2,1).MergeCellsTrue
Cells(3,1).MergeArea.Cells(1,1)为B”。 Cells(3,2).MergeArea.Cells(1,1)是 ” - -”。 Cells(3,1).MergeCellsFalse

如果您使用循环遍历单元格,请考虑使用 aWhileDo代替 a For,因为您可以为每次迭代增加不同的数字:

Dim rowCurrent AS Long
rowCurrent = 1
While Cells(rowCurrent,1).Value <> ""
    If Cells(rowCurrent,2).MergeArea.Cells(1,1).Value = "---" Then
        Select Case Cells(rowCurrent,1).MergeArea.Cells(1,1).Value
            Case "A"
                'concatenate something
            Case "B"
                'concatenate something else
            Case "C"
                'concatenate a third thing
            Case Else
                'throw an error?
        End Select
    End If
    'Skip the rest of the merged cell
    rowCurrent = rowCurrent + Cells(rowCurrent,1).MergeArea.Rows.Count
Wend

推荐阅读