简体   繁体   中英

Range.Value = “” type mismatch

I am trying to write some code to format a series of worksheets into a standardized format. To do this, I want to remove blank rows, delete leading spaces, and remove ";*" that start a lot of lines. Upon trying to see if aRow.Value = "", meaning there is no text in the row, a type mismatch error is always returned.

I have tried many different solutions from the internet, but none seem to work.

Sub Format()
    Dim ws As Worksheet
    Dim aRow As Range
    Dim r As Integer
    Dim cel As String

    For Each ws In ThisWorkbook.Worksheets
        For Each aRow In ws.UsedRange.Rows
            If ws.Name = "Sheet1" Then
                Exit For
            End If
            If aRow.Value = "" Then
                aRow.Delete
            End If
            If aRow.Value = " " Then
                aRow.Delete
            End If
            If Left(aRow.Value2, 2) = ";*" Then
                aRow.Value = Right(aRow.Value2, Len(aRow.Value2) - 2)
            Else
                aRow.Delete
            End If
            cel = "A" & aRow.Row
            aRow.Value = Application.WorksheetFunction.Trim(Range(cel).Value)
            If aRow.Value = Empty Then
                aRow.Delete
            End If
        Next
    Next
End Sub

Row represents an entire row in Excel and not a cell. You can not assigning a string value ("") to a row.

In your case, you want to check if the first cell equals to some value. Instead of checking aRow.Value= use aRow.Cells(1).Value .

Once you detected the row to delete, use aRow.Clear() to clear all row content.

Welcome to SO. I think you could replace line

For Each aRow In ws.UsedRange.Rows

by this:

For Each aRow In ws.UsedRange.Columns(1).Cells

That way, you will loop trough each cell of first column.

To delete an entire row, then you could use aRow.EntireRow.Delete

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM