为什么这个xls vba select有时会失败 – 在电子表格中没有改变

有人可以告诉我,如果我编码这个不好。 这种select似乎有时失败。 通过这个我的意思是我没有改变xls本身,但我可能只是检查数据,然后重新运行调用例程,它可能会失败,“范围类select方法失败”

我的这个例程的目标是改变一列数据的颜色。 从第1行到最后一行使用。 当这运行

cnum = 16 < – 这是我想突出显示的列号

lrow = 1418 < – 这是数据的最后一行

Sub HighlightColumn(colname As String, sheet As Worksheet, color As Long) Dim cnum As Integer Dim lrow As Long Dim lcol As Integer Dim r As Range lcol = sheet.UsedRange.Columns.Count lrow = RowCount(sheet) 'get column number cnum with the name colname For i = 1 To lcol If (sheet.Cells(1, i).Value = colname) Then cnum = i Next i 'create range Set r = sheet.Range(sheet.Cells(1, cnum), sheet.Cells(lrow, cnum)) r.Select 'this is the statement that fails 'set the color Selection.Interior.color = color End Sub 

“Range.Select”方法需要select的工作表是可见的。

 'create range Set r = sheet.Range(sheet.Cells(1, cnum), sheet.Cells(lrow, cnum)) ' add the following command and r.Select below will work just fine sheet.Activate r.Select 'this is the statement that fails 'set the color 

但是,为什么不呢

 r.Interior.color = color 

并完成它?