VBA通过.SpecialCells(xlCellTypeVisible)合并自动过滤的单元格.Range

时间:2016-03-18 13:56:37

标签: excel-vba merge autofilter vba excel

我有一个我的用户已经上过的课程列表,我想添加对他们拥有的车辆的访问权限,以及公司是否已激活他们的徽章以使用车辆(叉车等)。所以我想为用户合并所有类的行,然后只有一个居中的答案。当我逐步完成它看起来工作但最终结果是整个数据列被合并。我的问题是我的语法有错吗?或者我尝试做一些在Excel 2013中无法完成的事情。

我正在使用的代码:

With Range("A1:K" & LastRow)
  For i = 1 To UBound(FleetID, 1)
    .AutoFilter Field:=5, Criteria1:=FleetID(i)

    LastFilteredRow = .SpecialCells(xlCellTypeVisible).Cells(Rows.Count, "A").End(xlUp).Row
    If LastFilteredRow > 1 Then
     With .SpecialCells(xlCellTypeVisible).Range("R2:R" & LastFilteredRow)
       .Select
       .Merge
       If FleetClass(i) = "Operator" Then .Value = "Standard" Else .Value = FleetClass(i)
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
     End With 'std
     With .SpecialCells(xlCellTypeVisible).Range("S2:S" & LastFilteredRow)
       .Select
       .Merge
       .Value = FleetAct(i)
       .HorizontalAlignment = xlCenter
       .VerticalAlignment = xlCenter
     End With ' ' active
    End If
  Next i
   .Columns("A:U").AutoFit
   .Columns("E").ColumnWidth = 11
   .Columns("H:I").ColumnWidth = 11
   .Columns("N:N").ColumnWidth = 2
 End With   'Range("A1:K" & LastRow)

我的结果如下:

without merge

with merge

1 个答案:

答案 0 :(得分:0)

我发现我在这段代码中有2个错误。第一个错误是我的范围不正确,虽然它似乎没有打破合并,但确实打破了我后来添加的代码。我在特殊细胞之后使用了Range,因此将细胞从片材的开头合并到我的可见细胞的末端,而不是合并我范围内的可见细胞,因此所需的代码是

With Range("A1:T" & LastRow)
    For i = 1 To UBound(FleetID, 1)
      .AutoFilter Field:=5, Criteria1:=FleetID(i)
      LastFilteredRow = .SpecialCells(xlCellTypeVisible).Cells(Rows.Count, "A").End(xlUp).Row
      If LastFilteredRow > 1 Then
       With .Range("R2:R" & LastFilteredRow).SpecialCells(xlCellTypeVisible)
         .Merge
         If FleetClass(i) = "Operator" Then .Value = "Standard" Else .Value = FleetClass(i)
          .HorizontalAlignment = xlCenter
          .VerticalAlignment = xlCenter
       End With 'std
       With .Range("S2:S" & LastFilteredRow).SpecialCells(xlCellTypeVisible)
         .Merge
         .Value = FleetAct(i)
         .HorizontalAlignment = xlCenter
         .VerticalAlignment = xlCenter
       End With ' ' active
      End If
    Next i
   .Columns("A:U").AutoFit
   .Columns("E").ColumnWidth = 11
   .Columns("H:I").ColumnWidth = 11
   .Columns("N:N").ColumnWidth = 2
 End With   'Range("A1:T" & LastRow)