2012-12-22 118 views
0

我寫了一個代碼來刪除Excel表中的行,但它給了我一個錯誤,如主題中所述。VbScript拋出一個錯誤「未知的運行時錯誤」

CODE

Sub ChildPidDelt(ob3,DeletArr) 

Dim height,row,str,i 
Dim dataArray 
Dim d 
height = objExcel1.Application.WorksheetFunction.CountA(ob3.Columns(1)) 
'MsgBox(height) 
ReDim dataArray(height - 2, 0) ' -1 for 0 index, -1 for the first row as header row, excluded 
str = "" 
dataArray = ob3.Range(ob3.Cells(2, 1),ob3.Cells(height, 1)).Value 
Set d = CreateObject("scripting.dictionary") 
MsgBox(LBound(DeletArr) & ":" & UBound(DeletArr)) 
For i = LBound(DeletArr) To UBound(DeletArr) 
    If Not d.exists(DeletArr(i)) Then 
     d(DeletArr(i)) = 0 
    End If 
Next 
MsgBox(LBound(dataArray,1) & ":" & UBound(dataArray,1)) 
For i = LBound(dataArray, 1) To UBound(dataArray, 1) 
    If d.exists(dataArray(i, 1)) Then 

     str = str & (i+1) & ":" & (i+1) & "," 

    Else 
     'found = False 
    End If 
Next 
If Len(str) > 0 Then 
    MsgBox(Len(str)) 
    str = Mid(str, 1, Len(str) - 1) 
    MsgBox(str) 
    ob3.Range(str).Delete 

End If 

End Sub 

請看以下調試屏幕:

screen1 Screen2 Screen3 Screen4 Screen5

你能幫助我在這裏說的是什麼原因?

回答

1

Range()無法處理超過255個字符的字符串。

您可以通過將您的刪除分爲幾部分來解決此問題。這裏有一個簡單的方法來做到這一點:你最後MSGBOX

dim x 
dim rangesToRemove 
rangesToRemove = Split(str,",") 
for x = UBOUND(rangesToRemove) to LBOUND(RangesToRemove) Step -1 
    ob3.Range(rangesToRemove(x)).delete 
next 

編輯後直接到位:好吧,由於您的評論這裏是一個更復雜的方式,將打破刪除成塊。

dim x 
dim rangesToRemove 
dim strToRemove : strToRemove = "" 
rangesToRemove = Split(str,",") 
for x = UBOUND(rangesToRemove) to LBOUND(RangesToRemove) Step -1 
    strToRemove = strToRemove & rangesToRemove(x) 
    If Len(strToRemove) > 200 then 
     ob3.Range(strToRemove).delete 
     strToRemove = "" 
    else 
     strToRemove = strToRemove & "," 
    end if 
next 
If len(strToRemove) > 0 then 
    strToRemove = Left(strToRemove, Len(strToRemove) -1) 
    ob3.Range(strToRemove).delete 
end if 
+0

這樣刪除行,反正可以刪除不需要的行,因爲刪除會導致行向上移動?有更快的過程嗎?它會一個一個地刪除對嗎? –

+1

好吧,顯然你可以把它分解成大塊......我更新以顯示一個可能的方式來做到這一點。 –

+0

不錯的一個,只是爲了確認它會是'UBOUND(rangesToRemove)'還是'UBOUND(rangesToRemove)-1'? –