excel - 对象 'Range' 的方法 '_Global' 失败。错误

标签 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

最后,它检查numNull(行中空条目的数量)是否=totalRows 减去标题。我一直在工作,直到出现 If Range(location).Select = "" 语句。现在编译器说:

Method 'Range' of object '_Global' failed

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

最佳答案

当您应该使用 .Value 时,您的代码却使用了 .Select

这可能会更快:

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

关于excel - 对象 'Range' 的方法 '_Global' 失败。错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7747728/

相关文章:

javascript - 通过脚本使用Office365 Excel打开CSV

vba - 如果单元格值发生更改,请将值复制到另一个工作表

excel - 如何在 VBA 中获取行范围 2 :60 and column range D:H 中单元格的最大值

java - Apache POI - 如何注册一个函数

arrays - Excel公式获取单元格中分隔值的最大长度

vba - 使用偏移量查找空单元格并粘贴值范围

mysql - 通过 MySQL Workbench 的 "Table Data Import Wizard"导入带有转义引号的 CSV 文件

excel - ADO:Excel:是否可以在表名上打开记录集?

excel - 更改代码以允许选择多个文件

excel - VBA Excel 数据表单不显示正确的输入和字段