我有一个宏,可从五个工作表中提取数据并将其聚合为两个新的工作表。目前,我的代码在我的第一个新工作表中的各列之间循环,并合并和居中。但是,在第二个工作表中使用相同的代码块来执行此操作时遇到了麻烦。看起来该代码是特定于活动工作表的,我正在尝试将其设置为其他工作表。
Dim varTestVal4 As Variant
Dim intRowCount4 As Integer
Dim intAdjustment4 As Integer
ActiveSheet.Range("D1").Select
While Selection.Offset(1, 0).Value <> ""
intRowCount4 = 1
varTestVal4 = Selection.Value
While Selection.Offset(1, 0).Value = varTestVal4
intRowCount4 = intRowCount4 + 1
Selection.Offset(1, 0).Select
Selection.ClearContents
Wend
intAdjustment4 = (intRowCount4 * -1) + 1
Selection.Offset(intAdjustment4, 0).Select
Selection.Resize(intRowCount4, 1).Select
With Selection
.Merge
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
End With
Selection.Offset(1, 0).Resize(1, 1).Select
Wend
答案 0 :(得分:1)
尝试使用with语句来帮助指导正在发生的事情,例如:
With Sheets("NameOfSheet")
While .Cells(2,"D").Value <> ""
intRowCount4 = 1
varTestVal4 = .Cells(1,"D").Value
While .Cells(2,"D").Value = varTestVal4
intRowCount4 = intRowCount4 + 1
.Cells(2,"D").ClearContents
Wend
intAdjustment4 = (intRowCount4 * -1) + 1
With .Range(.Cells(intAdjustment4, "D"),.Cells(intAdjustment4, "E")) 'VERIFY THIS IS THE INTENDED RANGE
.Merge
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
End With
Wend
End With
您要在分配varTestVal4之前查看一下ISNUMERIC吗?然后,您可以将该变量调为long或integer。
编辑1::更改范围,旨在合并为intAdjustment4所指示的行上的列A至列C:
With Sheets("NameOfSheet")
While .Cells(2,"D").Value <> ""
intRowCount4 = 1
varTestVal4 = .Cells(1,"D").Value
While .Cells(2,"D").Value = varTestVal4
intRowCount4 = intRowCount4 + 1
.Cells(2,"D").ClearContents
Wend
intAdjustment4 = (intRowCount4 * -1) + 1
With .Range(.Cells(intAdjustment4, "A"),.Cells(intAdjustment4, "C"))
.MergeCells = True
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
End With
Wend
End With