1

我对 VBA 有点陌生,遇到了一个我无法解决的运行时错误。我有以下代码

Dim vRange As Range
Sheets("Vert E").Cells.FormatConditions.Delete
With Sheets("Vert E")
    Set vRange = .Range(.Cells(2, 2))
End With

vRange.Select

最后一行 vRange.Select 抛出一个错误,显示运行时错误“1004”:应用程序定义的或对象定义的错误。有任何想法吗?

4

2 回答 2

1

A couple of things:

1) Remove .Range(_) around .Cells(2,2): it is unnecessary

2) Move the With further up

3) Range.Select can only be used if the Range's worksheet is the active sheet. So to confirm it, add a like .Activate above vRange.Select, and move the End With to below vRange.Select.

Like:

Dim vRange As Range
With Sheets("Vert E")
    .Cells.FormatConditions.Delete
    Set vRange = .Cells(2, 2)
    .Activate
    vRange.Select
End With

Hope that helps

于 2013-08-12T14:34:57.557 回答
1

Shorter and neater way of doing it

 Dim vRange As Range
 Dim ws as Worksheet
 Set ws = Sheets("Vert E")
 ws.Cells.FormatConditions.Delete
 Set vRange = ws.Cells(2, 2)
 ws.Activate
 vRange.Select

note: avoid using Select

Update:

To apply some formatting to a cell without Selecting it use

below example changes the color of the cell

vRange.Interior.Color = RGB(200, 100, 50)

In VBE just type vRange.Interior. and make use of the VBE Intellisense which should help you a bit by listing the available properties of the Interior class.

The best way to apply formatting to a cell is to do it while recording a macro and then editing the code in the VBE.

于 2013-08-12T14:35:24.507 回答