首页 > 解决方案 > 仅在首次运行期间的 Excel VBA 错误代码

问题描述

我尝试了几种方法来消除我的 VBA 错误,但没有帮助。第一次运行时,会出现错误代码9。再次运行时,代码运行正常。我有另一个没有错误的代码,但在第一次运行时没有正确执行 VBA 代码。再次运行代码后,它会正确执行 VBA 代码。

我试过用 F8 来调试问题,我试过循环。

Sub TXNFont()

Dim Firstrow As Long
    Dim Lastrow As Long
    Dim Lrow As Long
    Dim CalcMode As Long
    Dim lastColumn As Integer
    Dim rng As Range
    Set rng = ActiveSheet.Cells

    Sheets("TXN Speed").Select

    lastColumn = rng.Find(What:="*", After:=rng.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False).Column

    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
    End With

    Sheets("TXN Speed").Select
    Cells.Select
       With ActiveSheet
        .Select
        Firstrow = .UsedRange.Cells(1).Row
        Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row
          For Lrow = Lastrow To Firstrow Step -1
            With .Cells(Lrow, lastColumn)
                If Not IsError(.Value) Then
                    If .Value > 3500 Then .EntireRow.Font.Color = RGB(255, 0, 0)
              End If
            End With
        Next Lrow
    End With
    With Application
             .Calculation = CalcMode
    End With

    Sheets("TXN Speed").Select
    With ActiveSheet
        .Select
        Range("A1:A5").EntireRow.Font.Color = RGB(0, 0, 0)
        End With

End Sub

Sub NetFont()

    Dim Firstrow As Long
    Dim Lastrow As Long
    Dim Lrow As Long
    Dim CalcMode As Long
    Dim lastColumn As Integer
    Dim rng As Range
    Set rng = ActiveSheet.Cells

    With Sheets("Network").Select

    Cells.Select
    With Selection.Font
        .ThemeColor = xlThemeColorLight1
        .TintAndShade = 0
    End With

    lastColumn = rng.Find(What:="*", After:=rng.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False).Column
    Cells.Select


    Cells.Select
     With ActiveSheet
        .Select
        Firstrow = .UsedRange.Cells(1).Row
        Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row

          For Lrow = Lastrow To Firstrow Step -1
            With .Cells(Lrow, lastColumn)
                If Not IsError(.Value) Then
                    If .Value < 10 Then .EntireRow.Font.Color = RGB(255, 0, 0)
                End If
            End With
        Next Lrow
    End With

    With Application
             .Calculation = CalcMode
    End With

    Sheets("Network").Select
    With ActiveSheet
        .Select
        Range("A1:A5").EntireRow.Font.Color = RGB(0, 0, 0)
    End With
    End With

End Sub

Sub TXNFont()第一次运行时会出错,但如果我再次运行,将毫无问题地执行代码。

Sub NetFont() 将在第一次运行时执行错误的编码,但如果我再次点击运行将正确执行代码。

这些代码链接到另一个运行良好且没有问题的 VBA 代码。我希望我制作的代码在第一次运行时运行顺利,没有错误。在此先感谢人们!

标签: excelvba

解决方案


推荐阅读