在Excel中使用VBA进行边框,单元格保留和自动换行

时间:2019-03-11 18:24:17

标签: excel vba

我想将复制的单元格设置为所有边框的格式,顶部对齐单元格,左侧对齐单元格,以及自动换行。

对于我尝试过的边界

With rng.Borders
  .LineStyle = xlContinuous

当前宏:

Sub Copy_Data()
    Dim Src As Worksheet, Dst As Worksheet
    Dim LastRow As Long, r As Range
    Dim CopyRange As Range

    Set Src = Sheets("Template")
    Set Dst = Sheets("Report")

    LastRow = Src.Cells(Cells.Rows.Count, "B").Row

    For Each r In Src.Range("B2:B" & LastRow)
        If r.Value = "Planning" Or r.Value = "On Hold" Or r.Value = "Planning" Or r.Value = "Gathering Info" Or r.Value = "" Then
            If CopyRange Is Nothing Then
                Set CopyRange = r.EntireRow
            Else
                Set CopyRange = Union(CopyRange, r.EntireRow)
            End If
        End If
    Next r

    If Not CopyRange Is Nothing Then
        CopyRange.Copy Dst.Range("A3")
    End If

End Sub

1 个答案:

答案 0 :(得分:0)

如果您录制宏,则会得到类似的内容

for (int i = 0; i < lb.Length; i++)
    {
        lb[i] = new Label();
        btn[i] = new Button();
        btn[i].Clicked += (sender, e) => Button_Clicked(sender, e, i); 
        //Here i is to pass the index to event handler Button_Clicked; 
    }

上面的代码也可以写成。注意我们如何使用循环创建边框。检查Range("A1:C10").Select Selection.Borders(xlDiagonalDown).LineStyle = xlNone Selection.Borders(xlDiagonalUp).LineStyle = xlNone With Selection.Borders(xlEdgeLeft) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlEdgeTop) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlEdgeBottom) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlEdgeRight) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlInsideVertical) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With Selection.Borders(xlInsideHorizontal) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With 的值是什么。然后,您将了解我们如何使用循环。

xlEdgeLeft, xlEdgeTop, xlEdgeBottom.. etc

类似地,用于环绕文本和单元格对齐,只需记录一个宏并编辑代码即可满足您的需求:)