对象'_Global'的方法'范围'失败.错误

fra*_*lin 3 excel vba excel-vba

我正在尝试让Excel找出工作表的哪些列是空白的.最终的想法是让它删除完全空白的列.这是我到目前为止的代码:

Sub Macro2()
'
' Macro2 Macro
'
Dim totalCols As Integer
Dim totalRows As Integer

totalCols = ActiveSheet.UsedRange.Columns.Count
totalRows = ActiveSheet.UsedRange.Rows.Count

Dim i As Integer
Dim j As Integer
Dim numNull As Integer

For i = 1 To totalCols
    For j = 2 To totalRows
        Dim location As String
        location = "R" & i & ":" & "C" & j
        If Range(location).Select = "" Then
            numNull = numNull + 1
        End If
    Next j
    If numNull = totalRows - 1 Then
        MsgBox ("Column " & i & "is null")
    End If
Next i

End Sub
Run Code Online (Sandbox Code Playgroud)

最后,它检查是否numNull(行中的空条目数)= totalRows减去标题.我一直在努力直到声明If Range(location).Select = "".现在编译器说:

对象'_Global'的方法'范围'失败

有谁知道这意味着什么或我如何解决它?

Tim*_*ams 5

.Select应该在使用时 使用您的代码.Value

这可能会更快:

Sub Tester()

    Dim col As Range, ur As Range
    Dim numRows As Long, numCols As Long, i As Long, awf

    Set awf = Application.WorksheetFunction
    Set ur = ActiveSheet.UsedRange

    numRows = ur.Rows.Count
    numCols = ur.Columns.Count

    'edit: account for header row...
    Set ur = ur.Offset(1,0).Resize(numRows-1, numCols)
    numRows = numRows - 1

    For i = numCols To 1 Step -1
        Set col = ur.Columns(i)
        If awf.CountBlank(col) = numRows Then
            MsgBox "Column #" & col.Column & " is empty"
            'col.EntireColumn.Delete
        End If
    Next i

End Sub
Run Code Online (Sandbox Code Playgroud)