Excel 范围类的删除方法失败-错误
我使用以下代码将行从数据库检索到excel电子表格:Excel 范围类的删除方法失败-错误,excel,vba,Excel,Vba,我使用以下代码将行从数据库检索到excel电子表格: Public Sub Button1_Click() ActiveSheet.Unprotect ' This will unprotect the whole sheet Dim sQry As String Dim iRows As Integer Dim iCols As Integer Dim SQL As String On Error GoTo ErrHandler 'Clear worksheet Call C
Public Sub Button1_Click()
ActiveSheet.Unprotect ' This will unprotect the whole sheet
Dim sQry As String
Dim iRows As Integer
Dim iCols As Integer
Dim SQL As String
On Error GoTo ErrHandler
'Clear worksheet
Call ClearExistingRows(4)
'Create ADODB Recordset for retrieved data
Call DBConnection.OpenDBConnection
'Create Recordset
Dim rsMY_Resources As ADODB.Recordset
Set rsMY_Resources = New ADODB.Recordset
SQL = "SELECT EmpID, EName, [Grouping], CCNum, CCName, ResTypeNum, ResName, Status from Employee_FTE Order by Status"
'Query the database
rsMY_Resources.Open SQL, DBConnection.oConn, adOpenStatic, adLockReadOnly
If rsMY_Resources.EOF = True Then
MsgBox ("No record found in database")
Exit Sub
End If
'Fill excel active sheet, starting from row# 3
iRows = 3
For iCols = 0 To rsMY_Resources.Fields.Count - 1
ActiveSheet.Cells(iRows, iCols + 1).Value = rsMY_Resources.Fields(iCols).Name
Next
ActiveSheet.Range(ActiveSheet.Cells(iRows, 1), ActiveSheet.Cells(iRows, rsMY_Resources.Fields.Count)).Font.Bold = True
iRows = iRows + 1
ActiveSheet.Range("A" + CStr(iRows)).CopyFromRecordset rsMY_Resources
iRows = rsMY_Resources.RecordCount
'Clean up
rsMY_Resources.Close:
Set rsMY_Resources = Nothing
Call DBConnection.CloseDBConnection
MsgBox (CStr(iRows) + " records have been retrieved from the database!")
Columns("B:H").Select
Selection.Locked = False
ActiveSheet.Protect
Exit Sub
ErrHandler:
MsgBox (Error)
End Sub
Public Sub ClearExistingRows(lRowStart As Long)
Dim lLastRow As Long
Dim iLastCol As Integer
If (Not (Cells.Find("*", Range("A1"), xlFormulas, , xlByRows, xlPrevious) Is Nothing)) Then
lLastRow = Cells.Find("*", Range("A1"), xlFormulas, , xlByRows, xlPrevious).Row ' Find the last row with data
If (lLastRow >= lRowStart) Then
iLastCol = Cells.Find("*", Range("A1"), xlFormulas, , xlByColumns, xlPrevious).Column ' Find the last column with data
Range(Cells(lRowStart, 1), Cells(lLastRow, iLastCol)).Select
Selection.EntireRow.Delete
End If
End If
End Sub
但是,当我编写此代码以锁定整行时,如果H列的值为“InActive”,则会出现错误-Delete方法或range类失败
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
For Each cell In Range("A4:H500")
If cell.Value = "InActive" Then
ActiveSheet.Unprotect
cell.EntireRow.Locked = True
ActiveSheet.Protect
End If
Next cell
End Sub
请让我知道如何修复此错误
谢谢,
Hema“当我编写此代码以锁定…时,出现错误-Delete方法或range类失败。”这怎么可能?您没有试图删除
工作表\u SelectionChange
中的任何内容。你到底是从哪里得到错误的?哪一个例程,哪一行?“ClearExistingRows”子命令使用delete。那么问题出在哪里?锁定某些单元格并保护工作表,因此不能删除至少包含一个受保护单元格的任何区域也就不足为奇了。