Excel VBA基于查找值更改行高

时间:2017-05-18 09:57:01

标签: excel vba excel-vba find

我有一张2张工作簿。第一列有2列数据。第二个是格式化的时间表。我想在计划的第一列数据中找到值:

替换第二列中的数据 使用新值增加单元格的行高度5。 将Schedule中所有单元格的Font更改为Calibri。

这是我到目前为止所做的,但它不起作用:

Public Sub FindReplace()
    Dim AllCells As Range
    Dim myList As Range
    Dim myRange As Range
    Dim myHeight As Double

    Set AllCells = Sheets("Sheet 1").Cells
    AllCells.Font.Name = "Calibri"

    Set myList = Sheets("FindReplace").Range("A1:C200")
    Set myRange = Sheets("Sheet 1").Cells

    For Each cel In myList.Columns(1).Cells
        myRange.Select
        Selection.Find(What:=cel.Value, LookIn:=xlFormulas, LookAt:=xlWhole).Activate
        ActiveCell.RowHeight = myHeight
        myHeight = myHeight + 5
        Selection.RowHeight = myHeight

        myRange.Replace cel.Value, cel.Offset(0, 2), LookAt:=xlWhole     
    Next cel
End Sub

请帮忙

2 个答案:

答案 0 :(得分:0)

这样的事情可能有用:

Option Explicit

Public Sub FindReplace()

    Dim AllCells        As Range
    Dim myList          As Range
    Dim myRange         As Range
    Dim myHeight        As Double
    Dim cel             'not declared in your code, but its a good idea to do it

    Set AllCells = Sheets("T3").Cells
    AllCells.Font.Name = "Calibri"

    Set myList = Sheets("T2").Range("A1:C200")
    Set myRange = Sheets("T3").Cells

    For Each cel In myList.Columns(1).Cells
        myRange.Parent.Activate
        myRange.Select
        'Selection.Find(What:=cel.Value, LookIn:=xlFormulas, LookAt:=xlWhole).Activate

        myHeight = myHeight + 5

        If myHeight < 410 Then
            'Selection.RowHeight = myHeight
            ActiveCell.RowHeight = myHeight
        End If
        myRange.Replace cel.Value, cel.Offset(0, 2), LookAt:=xlWhole
    Next cel
End Sub

改变了什么?

  • 表格的名称。
  • 使用cel
  • 激活myRange.Parent.Activate元素的活动工作表
  • 介绍410高度的条件。
  • 明确选项

通常,代码质量不高,因为它使用SelectActivate,这是出于性能和调试原因而违反最佳做法的。

答案 1 :(得分:0)

试试这个:

Option Explicit

Public Sub FindReplace()

Dim myList, myRange, CelA, celB As Range

Set myRange = Sheets("T3").Cells
myRange.Font.Name = "Calibri"
Set myList = Sheets("T2").Range("A1:c200")
For Each CelA In myList.Columns(1).Cells
    If CelA <> "" Then
        Set celB = myRange.Cells.Find(What:=CelA.Value, LookIn:=xlFormulas, LookAt:=xlWhole)
        If Not celB Is Nothing Then
            If celB.RowHeight < 410 Then celB.RowHeight = celB.RowHeight + 5
            myRange.Replace CelA.Value, CelA.Offset(0, 2), LookAt:=xlWhole
        End If
    End If
Next CelA
End Sub