>我必须合并 2 个单元格,其中范围在每次运行时都可能有所不同。我正在尝试使用以下代码,但代码存在一些错误,我无法识别。对于固定范围,它工作正常,但对于变量,它显示错误。行号是需要合并的单元格编号,每次运行都会有所不同:
Range("D" & line_no & ":" "E" & line_no & ).Select
Range("D" & line_no).Activate
With Selection
.VerticalAlignment = xlCenter
.HorizontalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = True
End With
我会尝试摆脱一般的Select
。你可以这样做:
With Range("D" & line_no & ":" & "E" & line_no)
.VerticalAlignment = xlCenter
.HorizontalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = True
End With
你的问题在于字符串连接。评论涵盖了这一部分。
如果在整个程序中使用此范围,我建议在变量中划定此范围:
定义字符串,它将指向所需的范围:Dim rng As String: rng = "D" & line_no & ":E" & line_no
,然后像这样使用它:
Range(rng).Select
Range(rng).Activate
或
定义范围并将范围存储在变量中而不是字符串中">
Dim rng As Range
Set rng = Range("D" & line_no & ":E" & line_no)
rng.Select
rng.Activate
'...