我正在尝试让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 = ""
。现在编译器说:
对象'_Global'的方法'范围'失败
有谁知道这意味着什么或我如何解决它?
答案 0 :(得分: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
答案 1 :(得分:2)
此时'Range'不引用实例化对象。 Range类不能以这种方式静态使用 - 您必须实例化一个Range对象,通常是通过调用适当的对象的工厂方法。可能有其他方法可以做到,但我通常会调用ActiveSheet.Range。
如上面提到的蒂姆·威廉姆斯所说,你应该使用.Value而不是.Select;我不确定是什么。选择返回,MSDN引用只是说数据类型变体。
我不在Windows机器上进行测试,但请尝试:
If ActiveSheet.Range(location).Value = "" Then