Sub Sample()
Dim wsDiff As Worksheet, wsSheet As Worksheet, wsColorIndex As Worksheet
Dim lRow As Long, i As Long, j As Integer
Dim delentrysheet As String
Dim delentrycell As String
Dim delentrycolindex As Integer
Set wsDiff = Sheets("Differences")
Set wsColorIndex = Sheets("VERSION LOG")
lRow = wsDiff.Range("E" & wsDiff.Rows.Count).End(xlUp).row
delentrycolindex = wsColorIndex.Range("I3").Interior.ColorIndex
For i = 2 To lRow
If wsDiff.Range("E" & i).Value = "Entered Value Deleted." Then
delentrysheet = wsDiff.Range("A" & i).Value
delentrycell = wsDiff.Range("B" & i)
Set wsSheet = Sheets(delentrysheet)
With wsSheet
.Range(delentrycell).Interior.ColorIndex = delentrycolindex
End With
End If
Next
End Sub
运行此程序时出错。
"方法'范围'对象' _Worksheet'失败。
有人可以帮忙吗?感谢。
答案 0 :(得分:0)
您可以在分配之前检查delentrysheet是否存在。
我使用了一个函数:
Public function WorksheetExists(byval strSheet as string) as Boolean
Dim wksCurr as excel.worksheet
WorksheetExists = false
For each wksCurr in thisworkbook.worksheets
If wksCurr.name = strSheet then
WorksheetExists = true
Exit for
End if
Next wksCurr
End function
在您的代码中,请检查:
如果是worksheetexists(delentrysheet)那么 设置xxxx 其他 如果
结束使用一些代码来处理异常,也许是一个消息框
答案 1 :(得分:0)
将delentrycell
值替换为(行,列),然后尝试以下操作。
而不是使用以下代码:
.Range(delentrycell).Interior.ColorIndex = delentrycolindex
尝试使用以下代码:
.Cells(1,1).Interior.ColorIndex = delentrycolindex
如果Cells(row,column)
正确表示Cells(delentrycell)
,您可以将delentrycell
替换为(Row,Column)
。