我希望你一切都好。我正在接触Stack Overflow社区,因为我目前在Excel中使用VBA编程时遇到初学者问题。我确实在努力缩短和协调公司中的卓越流程。
上下文
在其他命令中,我试图对宏进行编程以使其在选择中居中(这可能非常有用,并且右键单击“格式”等会很麻烦)。我在网上找到了代码,并且在某种程度上可以正常工作。
问题
步骤1
我选择一些单元格。我运行宏(请参见下面的代码)。它以选择为中心。
步骤2
我选择更大范围的单元格。它仍然以选择为中心。
步骤3
我选择较小范围的单元格。 它不在选择中居中。
我曾尝试过这么远
我尝试使用Selection.ClearFormats命令;没用(可能使用得不好)。
代码
Sub center_across_selection()
'
' center_across_selection Macro
'
' Touche de raccourci du clavier: Ctrl+Shift+M
'
With Selection
If .HorizontalAlignment = xlCenterAcrossSelection Then
.HorizontalAlignment = xlGeneral
'converts regular text to centered across selection
Else
Selection.HorizontalAlignment = xlCenterAcrossSelection
End If
End With
End Sub
谢谢您的帮助!
答案 0 :(得分:1)
似乎每个单独的单元格都将获得“选择中的中心”对齐方式,如果您在已经具有该设置(但没有内容)的单元格旁边的单元格上设置该值,Excel将自动扩展“选择范围”包括其他单元格。
以下代码将显示所选单元格正下方的格式:
Sub center_across_selection()
Dim c As Range
With Selection
'show alignment "before"
For Each c In .Cells
c.Offset(1, 0) = c.HorizontalAlignment
Next c
Debug.Print .HorizontalAlignment = xlCenterAcrossSelection
If .HorizontalAlignment = xlCenterAcrossSelection Then
.HorizontalAlignment = xlGeneral
Else
.HorizontalAlignment = xlCenterAcrossSelection
End If
'show alignment "after"
For Each c In .Cells
c.Offset(2, 0) = c.HorizontalAlignment
Next c
End With
End Sub
要解决此问题,您可以立即检查所选内容中最后一个单元格右侧的单元格-如果将其设置为“跨选区中心”,则将其设置为其他内容。
Sub center_across_selection2()
Dim c As Range, rNext As Range
With Selection
If .HorizontalAlignment = xlCenterAcrossSelection Then
.HorizontalAlignment = xlGeneral
Else
'check whether the next cell to the right has CAS and is empty
Set rNext = .Cells(.Cells.Count).Offset(0, 1)
If rNext.HorizontalAlignment = xlCenterAcrossSelection _
And Len(rNext.Value) = 0 Then
rNext.HorizontalAlignment = xlGeneral
End If
.HorizontalAlignment = xlCenterAcrossSelection
End If
End With
End Sub
答案 1 :(得分:0)
您还可以使用函数来递归检查所选内容右侧的单元格:
Sub center_across_selection()
With Selection
If .Offset(0, 1).HorizontalAlignment = xlCenterAcrossSelection Then resetAlignment (.Offset(0, 1))
If .HorizontalAlignment = xlCenterAcrossSelection Then
.HorizontalAlignment = xlGeneral
'converts regular text to centered across selection
Else
Selection.HorizontalAlignment = xlCenterAcrossSelection
End If
End With
End Sub
Function resetAlignment(rng As Range)
rng.HorizontalAlignment = xlGeneral
If rng.Offset(0, 1).HorizontalAlignment = xlCenterAcrossSelection Then resetAlignment (rng.Offset(0, 1))
End Function