我正在尝试更改excel文件的数据,以便更轻松地导入到我的数据库中。我正在使用excel中的3个宏代码执行此操作。
这是代码:
1 - 删除两个第一列
Sub Del_Columns ()
Columns ("A:B").EntireColumn.Delete
End Sub
2 - 使用上述值填充最右侧的列,以新值结束。
Sub FillBlanks()
Dim wks As Worksheet
Dim rng As Range
Dim LastRow As Long
Dim col As Long
Set wks = ActiveSheet
with wks
col = .Range("M").Column
Set rng = .UsedRange
LastRow = .Cells.SpecialCells(xlCellTypeLastCell).Row
Set rng = Nothing
On Error Resume Next
Set rng = .Range(.Cells(2, col), .Cells(LastRow, col)) _
.Cells.SpecialCells(xlCellTypeBlanks))
On Error GoTo 0
If rng Is Nothing Then
MsgBox "No Blanks Found"
Exit Sub
Else
rng.FormulaR1C1 = "=R[-1]C"
End If
With .Cells(1, col).EntireColumn
.Value = .Value
End With
End With
End Sub
3 - 删除其中包含空单元格的所有行(以col F为例,用于在空行时删除整行。总是如此)
Sub DeleteBlankRows()
On Error Resume Next
Columns ("F").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub
摘要
这样做的时候,我在某些单元格上获得了#REF,我应该怎么做才能防止/修复这个问题?
也;这个代码对于Number 2更好(填充具有以上值的单元格):
Sub FillCellsFromAbove()
Application.ScreenUpdating = False
On Error Resume Next
With Columns(1)
.SpecialCells(xlCellTypeBlanks).Formula = "=R[-1]C"
.Value = .Value
End With
Err.Clear
Application.Updating = True
End Sub
您的第二个代码示例更好,但您确实使用了不同的公式样式。确保在代码的第2步中使用.FormulaR1C1
。
#REF错误几乎肯定与您在上面引用一行时删除行有关。您应该考虑寻找不同的引用方式,或者先删除要消除的行,然后创建公式。
如果这不是一个选项,并且您确定您总是希望单元格引用其上方的一行,则可以使用间接Excel功能。它会降低性能,但我认为这是你要做的。
在这种情况下,.Formula
或.FormulaR1C1
方法都可以使用:
.SpecialCells(xlCellTypeBlanks).Formula = "=Indirect(""R[-1]C"",FALSE)"