我试图让这段代码说出"如果第3列(C)中的单元格=单词" high"或"中"然后将第4列(D)中的匹配单元合并并居中,只有下面的单元格。然而,我现在的反应方式是通过.End(xlDown)将所有方式合并到底部。我不知道如何解决这个问题。这里有一个数据样本以及我希望它的外观:
以下是我一直在使用的VBA代码:
Sub Merge_Priority2()
Dim RgToMerge As String
For i = 1 To ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
RgToMerge = ""
If LCase(Cells(i, 3)) = "high" Or LCase(Cells(i, 3)) = "middle" Then
RgToMerge = "$D$" & Cells(i, 4).End(xlDown).Row & ":$D$" & i
With Range(RgToMerge)
.Merge
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
End With
Else
End If
Next i
End Sub
答案 0 :(得分:1)
我假设您使用.End(xlDown)
来选择下一行,但您可以摆脱它(如@MattCremeens建议的那样)。然后,对于范围的第二部分,向i
添加1以使其选择只有一个行,如下所示:
RgToMerge = "$D$" & i & ":$D$" & i + 1
对于第1行,RgToMerge
将显示为$D$1:$D$2
。完整的Sub看起来像这样:
Sub Merge_Priority2()
Dim RgToMerge As String
For i = 1 To ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
RgToMerge = ""
If LCase(Cells(i, 3)) = "high" Or LCase(Cells(i, 3)) = "middle" Then
RgToMerge = "$D$" & i & ":$D$" & i + 1
With Range(RgToMerge)
.Merge
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
End With
Else
End If
Next i
End Sub
答案 1 :(得分:1)
尝试根据行变量(i)
定义范围Sub Merge_Priority2()
Dim RgToMerge As Range
For i = 1 To ActiveSheet.Cells(Rows.Count, 3).End(xlUp).Row
If LCase(Cells(i, 3)) = "high" Or LCase(Cells(i, 3)) = "middle" Then
Set RgToMerge = ActiveSheet.Range(Cells(i, 4), Cells(i + 1, 4))
With RgToMerge
.Merge
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
End With
Else
End If
Next i
End Sub
答案 2 :(得分:0)
我稍微修改了你的代码。我觉得你太离谱了。
Sub Merge_Priority2() Dim RgToMerge作为范围
For i = 1 To ActiveSheet.Cells(Rows.Count, 3).End(xlUp).Row
If LCase(Cells(i, 3)) = "high" Or LCase(Cells(i, 3)) = "middle" Then
Set RgToMerge = Range(Cells(i, 3), Cells(i + 1, 3))
With RgToMerge
.Merge
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
End With
Else
End If
Next i
我假设相关数据在C栏。 结束子