为什么有时xls vba选择失败 - 电子表格没有变化?

时间:2017-09-26 22:22:21

标签: excel vba excel-vba 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

1 个答案:

答案 0 :(得分:2)

" Range.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

并完成它?