【问题标题】:How to solve run-time error in VBA Excel?如何解决 VBA Excel 中的运行时错误?
【发布时间】:2021-09-11 23:36:04
【问题描述】:

当我在 VBA Excel 中运行代码时。我得到运行时错误'1004'方法'范围'对象'_工作表失败。 这是代码。

Private Sub Worksheet_Change(ByVal Target As Range)

With Range("A" & firstTickerRow & ":A" & Rows.Count).Interior
    .Pattern = xlNone
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With

With Range("A" & firstTickerRow - 1 & ":A" & Rows.Count)
    .Borders(xlEdgeRight).LineStyle = xlNone
    .Borders(xlInsideHorizontal).LineStyle = xlNone
End With

lastRowColA = Cells(Rows.Count, "a").End(xlUp).Row

With Range("A" & firstTickerRow - 1 & ":A" & lastRowColA)
    .Borders(xlEdgeRight).LineStyle = xlContinuous
    .Borders(xlEdgeRight).Weight = xlMedium
    .Borders(xlEdgeBottom).LineStyle = xlContinuous
    .Borders(xlEdgeRight).Weight = xlMedium
    .Borders(xlEdgeBottom).Weight = xlMedium
End With

With Range("A" & firstTickerRow & ":A" & lastRowColA).Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .ThemeColor = xlThemeColorAccent1
    .TintAndShade = 0.799981688894314
    .PatternTintAndShade = 0
End With

结束子

【问题讨论】:

  • 什么是firstTickerRow
  • 哪一行报错了?
  • 第一行 @RBarryYoung - 'Private Sub Worksheet_Change(ByVal Target As Range)'
  • 您没有为firstTickerRow 赋值,因此它是0 并且没有0 行。
  • 对,正如@ScottCraner 所说,“A0:A99”是一个无效的范围地址,因为没有第 0 行。同样,稍后像“A-1:A88”这样的地址也是无效的。您需要确保构造的范围有效,或者使用错误处理来捕获并跳过错误的引用。

标签: excel vba


【解决方案1】:

在工作表更改事件中格式化

  • 您通常希望将其限制在某个范围内,例如本例中的列范围 (A)。这是在包含Intersect 的行中完成的。
  • 调整这两个常数。
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    
    Const tCol As String = "A"
    Const ftRow As Long = 2
    
    If Intersect(Target, Columns(tCol)) Is Nothing Then Exit Sub
    If ftRow < 2 Or ftRow > Rows.Count Then Exit Sub
    
    With Range(tCol & ftRow & ":" & tCol & Rows.Count).Interior
        .Pattern = xlNone
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
        
    With Range(tCol & ftRow - 1 & ":" & tCol & Rows.Count)
        .Borders(xlEdgeRight).LineStyle = xlNone
        .Borders(xlInsideHorizontal).LineStyle = xlNone
    End With
    
    Dim lRow As Long: lRow = Cells(Rows.Count, "A").End(xlUp).Row
    If lRow < ftRow Then Exit Sub
    
    With Range(tCol & ftRow - 1 & ":" & tCol & lRow)
        .Borders(xlEdgeRight).LineStyle = xlContinuous
        .Borders(xlEdgeRight).Weight = xlMedium
        .Borders(xlEdgeBottom).LineStyle = xlContinuous
        .Borders(xlEdgeBottom).Weight = xlMedium
    End With
    
    With Range(tCol & ftRow & ":" & tCol & lRow).Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent1
        .TintAndShade = 0.799981688894314
        .PatternTintAndShade = 0
    End With

End Sub

【讨论】:

    猜你喜欢
    • 2015-11-18
    • 2019-03-01
    • 1970-01-01
    • 2016-11-08
    • 2019-12-15
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 2016-11-09
    相关资源
    最近更新 更多