在VBA中添加新行故障

我已经写了下面的代码,在电子表格的一个部分的一个行范围内添加一个新行。 由于有几个这些部分,sBudgetLine作为范围(部分名称)的起始值被传入,并添加了额外的1以错过部分(date,说明和价格)的标题。

所有的工作正常,但是当行偶尔添加我已经硬编码格式不起作用,并增加了一个额外的行在页面下方,以及新的行是在正确的地方。

Sub AddNewAllocToSpendLine(sBudgetLine As String, Optional sSheetName As String = c_Alloc2SpendSheetName) Dim c As Range Dim N As Long Dim lastRow As Long Dim formula As Range Dim rng As Range With Worksheets(sSheetName) Set c = .Columns(1).Find(sBudgetLine, LookIn:=xlValues) If Not (c Is Nothing) Then lastRow = .Cells(c.Row, 2).End(xlDown).Row Worksheets(sSheetName).Activate Worksheets(sSheetName).Range("B" & lastRow + 1, "E" & lastRow + 1).Activate Selection.EntireRow.Insert Shift:=xlDown Selection.Range("B" & ActiveCell.Row, "E" & ActiveCell.Row).Interior.Color = RGB(255, 255, 255) With Selection.Range("B" & ActiveCell.Row, "D" & ActiveCell.Row).Borders .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = 1 End With Selection.Cells(1, 4).formula = "=IF(" & "D" & ActiveCell.Row & "="""","""",IF(" & "D" & ActiveCell.Row & ">14999.99,""Minimum 3 formal competitive tenders - inform PSU"",IF(" & "D" & ActiveCell.Row & ">2499.99,""Minimum 3 written quotes based on written specification"",IF(" & "D" & ActiveCell.Row & ">999.99,""Minimum 3 written quotes"",IF(" & "D" & ActiveCell.Row & ">499.99,""Minimum 3 oral quotes"",IF(" & "D" & ActiveCell.Row & ">249.99,""One written or verbal quote"",""One written or verbal quote""))))))" End If End With End Sub 

我已经尝试了各种各样,不能找出什么是错的,这可能是一个VBBA故障? 如果是这样的话,有没有更好的方式提供添加行的格式?

你用一个With … End With语句引用父工作表开始,然后似乎放弃它。 如果一个更大的单元块包含了你想要的单元。激活已经是.Selection,那么select不会改变,只有ActiveCell属性 。

最好避免使用Range .Select方法和Range.Activate方法完全¹ 。

 Sub AddNewAllocToSpendLine(sBudgetLine As String, Optional sSheetName As String = c_Alloc2SpendSheetName) Dim rw As Variant, nr As Long With Worksheets(sSheetName) rw = Application.Match(sBudgetLine, .Columns(1), 0) If Not IsError(rw) Then nr = .Cells(rw, "B").End(xlDown).Row + 1 .Rows(nr).EntireRow.Insert Shift:=xlDown With .Range(.Cells(nr, "B"), .Cells(nr, "E")) .Interior.Color = RGB(255, 255, 255) With .Borders .LineStyle = xlContinuous .Weight = xlThin .ColorIndex = 1 End With .Cells(1, 4).formula = _ "=IF(D" & nr & "=TEXT(,), TEXT(,), " & _ "IF(D" & nr & ">14999.99, ""Minimum 3 formal competitive tenders - inform PSU"", " & _ "IF(D" & nr & ">2499.99, ""Minimum 3 written quotes based on written specification"", " & _ "IF(D" & nr & ">999.99, ""Minimum 3 written quotes"", " & _ "IF(D" & nr & ">499.99, ""Minimum 3 oral quotes"", " & _ "IF(D" & nr & ">249.99, ""One written or verbal quote"", " & _ """One written or verbal quote""))))))" End With End If End With End Sub 

TEXT(,)只是一种书写方式,不必在string中写成""""


¹ 请参阅如何避免使用在Excel VBAmacros中select更多的方法来摆脱依靠select和激活来实现您的目标。