我正在尝试选择仅包含某些标题的列,删除所有其他标题,但我一直收到错误消息。它是Method 'Range' of object '_Global' failed
,它突出显示第七行代码(Range(Cells(1, Col)).Select
)。
任何帮助或建议将不胜感激 - 谢谢!
Dim Col As Integer
Col = 1
Range("A1").Select
While Selection.Value <> ""
If Selection.Value = "A" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "B" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "D" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "E" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "F" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "H" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "J" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "M" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "N" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "P" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "R" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "S" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "T" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "V" Then
Col = Col + 1
Range(Cells(1, Col)).Select
ElseIf Selection.Value = "X" Then
Col = Col + 1
Range(Cells(1, Col)).Select
Else: ActiveCell.EntireColumn.Delete
End If
Wend
答案 0 :(得分:2)
首先,错误是由仅使用一个Cell参数调用Range引起的。如果只有一个Cell,则必须附加Cell及其Address属性,因此该行应为Range(Cells(1,col).Address).Select
其次,根据您所描述的,您希望自己的代码可以执行,我不认为此代码会实际执行您的喜好。坦率地说,我无法真正告诉你甚至试图从代码本身做什么,所以要预先警告我的答案将修复错误调用,但似乎它不会像你一样运行一旦确实运行,我们就会期待。
答案 1 :(得分:2)
您也可以通过在问题部分中加入or
来轻松缩短if语句。
With Selection
If .Value = "A" or "B" or... ...Then...
Else...
End If
End With
希望这会有所帮助 - https://msdn.microsoft.com/en-us/library/752y8abs.aspx