EXCEL - VBA录制的宏给出运行时错误“1004”

问题描述 投票:1回答:2

我制作了一个简短的VBA代码,它基本上只是在单元格内自动填充文本/内容。我录制了这个宏,然后重新制作它,以便代码贯穿整个工作表:

Sub Macro3()
    Dim lastRowIndex As Integer
    Dim rowIndex As Integer
    lastRowIndex = 2600

For rowIndex = 0 To lastRowIndex
    If ActiveSheet.Cells(rowIndex, 1).Value <> "" Then
        If ActiveSheet.Rows(rowIndex).RowHeight < 10.7 Then
            If ActiveSheet.Rows(rowIndex).RowHeight > 8 Then
                ActiveSheet.Rows(rowIndex).Select
                With Selection
                    .HorizontalAlignment = xlGeneral
                    .VerticalAlignment = xlBottom
                    .WrapText = True
                    .Orientation = 0
                    .AddIndent = False
                    .IndentLevel = 0
                    .ShrinkToFit = False
                    .ReadingOrder = xlContext
                    .MergeCells = False
                End With
                Selection.Rows.AutoFit
            End If
        End If
    End If
Next rowIndex

结束子

应用程序在IF条件下停止。他们在那里是因为我不想影响所有细胞,只需要修改我需要的细胞。

当我尝试运行此代码时,它给我一个运行时错误“1004” - 应用程序定义或对象定义的错误。我不知道为什么...

我尝试将Option Explicit放在代码之上,因为我在某处读到它然后会为您提供有关错误的更详细信息,但这似乎也不起作用。我之前从未真正使用过VBA,所以我不知道错误的原因是什么。

(为什么上面代码的一部分向左移动?我无法修复它)

excel vba excel-vba
2个回答
0
投票

CELLS()索引从1开始,所以:

For rowIndex = 1 To lastRowIndex

(可能还有其他错误。)


0
投票
  1. 在代码顶部使用Option Explicit
  2. 给你的sub一个有意义的名字
  3. 如上所述,从1循环
  4. 使用显式工作表引用(不是活动表),并在With语句中保留它,然后使用内部的点运算符
  5. 使用vbNullString而不是空字符串文字""进行更快的比较
  6. If条件组合成一行以减少嵌套并增强可读性
  7. 使用With语句来保存对当前行的引用
  8. 使用Long而不是Integer处理行,将来这可能会冒更大数字的溢出
  9. 目前lastRowIndex是一个常数,因此声明如此

码:

Option Explicit
Public Sub FormatRows()
    Const lastRowIndex As Long = 2600
    Dim rowIndex As Long

    With ThisWorkbook.Worksheets("Sheet1")
        For rowIndex = 1 To lastRowIndex
            If Not .Cells(rowIndex, 1).Value <> vbNullString Then
                If .Rows(rowIndex).RowHeight > 8 And .Rows(rowIndex).RowHeight < 10.7 Then
                    With .Rows(rowIndex)
                        .HorizontalAlignment = xlGeneral
                        .VerticalAlignment = xlBottom
                        .WrapText = True
                        .Orientation = 0
                        .AddIndent = False
                        .IndentLevel = 0
                        .ShrinkToFit = False
                        .ReadingOrder = xlContext
                        .MergeCells = False
                        .AutoFit
                    End With
                End If
            End If
        Next
    End With
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.