在VBA中将特定String插入空单元格

时间:2017-03-27 14:03:41

标签: excel vba excel-vba

目标:使用字符串(" / N")填充工作表中的所有空单元格。

问题:在代码运行期间,由于某种原因,我不断出现类型不匹配问题。 此错误显示在该行:

If Worksheets("Comp").Cells(lRow, lColumn) = "" Then

问题:我做错了什么,有办法解决吗?

Obs1:我的工作表包含5千行和40列。前3行是标题(标识符),前3列总是有数据。

Obs2:工作表有不同类型的数据(数字,字符串,日期)

代码:

Sub n_slasher()

Dim i As Integer, j As Integer
Dim LastRow As Long, LastColumn As Long
Dim lRow As Long, lColumn As Long
Dim ws As Worksheet
Dim w As Workbook

Set w = ThisWorkbook

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

'find date limits
LastRow = Worksheets("Comp").Cells(Rows.Count, "A").End(xlUp).Row
LastColumn = Worksheets("Comp").Cells(1, Columns.Count).End(xlToLeft).Column

        For lColumn = 4 To LastColumn
            For lRow = 3 To LastRow
                If Worksheets("Comp").Cells(lRow, lColumn) = "" Then
                    Worksheets("Comp").Cells(lRow, lColumn) = "\N"     
                End If 
            Next lRow
        Next lColumn

Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic

End Sub

1 个答案:

答案 0 :(得分:1)

这是使用数组的版本

Sub n_slasher()

    Dim LastRow As Long, LastColumn As Long
    Dim lRow As Long, lColumn As Long
    Dim ws                    As Worksheet
    Dim w                     As Workbook
    Dim data

    Set w = ThisWorkbook

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
        .Calculation = xlCalculationManual
    End With
    Set ws = Worksheets("Comp")
    'find date limits

    With ws
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column

        data = .Range("D3", .Cells(LastRow, LastColumn)).Value2

        For lRow = 1 To UBound(data)
            For lColumn = 1 To UBound(data, 2)
                If Not IsError(data(lRow, lColumn)) Then If Len(data(lRow, lColumn)) = 0 Then data(lRow, lColumn) = "\N"
            Next lColumn
        Next lRow
        .Range("D3", .Cells(LastRow, LastColumn)).Value2 = data
    End With

    With Application
        .EnableEvents = True
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
    End With

End Sub