我试图让 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/