我制作了一个简短的VBA代码,它基本上只是在单元格内自动填充文本/内容。我录制了这个宏,然后重新制作它,以便代码贯穿整个工作表:
Sub Macro3() Dim lastRowIndex As Integer Dim rowIndex As Integer lastRowIndex = 2600For 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,所以我不知道错误的原因是什么。
(为什么上面代码的一部分向左移动?我无法修复它)
CELLS()索引从1开始,所以:
For rowIndex = 1 To lastRowIndex
(可能还有其他错误。)
Option Explicit
With
语句中保留它,然后使用内部的点运算符vbNullString
而不是空字符串文字""
进行更快的比较If
条件组合成一行以减少嵌套并增强可读性With
语句来保存对当前行的引用Long
而不是Integer
处理行,将来这可能会冒更大数字的溢出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