开发者

Method 'Range' of object '_Global' failed. error

I'm trying to get Excel to figure out which columns of a worksheet are blank. Eventually the idea is to get it to delete the completely blank columns. Here's the code I have so far:

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

At the end it checks to see if numNull (number of null entries in the row) = totalRows minus the header. I had it working up until the statement If Range(location).Select = "". Now the compiler says:

Method 'Range' of object '_Global' failed

Does anyone know what this means or how I can fix it?


Your code is using .Select when you should be using .Value

This might be faster though:

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


At this point 'Range' doesn't refer to an instantiated object. The Range class can't be used statically this way - you have to instantiate a Range object, usually by calling an appropriate object's factory method. There are probably other ways to do it, but I generally call ActiveSheet.Range.

As noted by Tim Williams above, you should probably be using .Value rather than .Select; I'm not at all sure what .Select returns, the MSDN reference just says data type variant.

I'm not at a Windows machine to test, but try:

If ActiveSheet.Range(location).Value = "" Then

MSDN Range Object Reference

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜