【问题标题】:VbScript throwing an error "Unknown runtime error"VbScript 抛出错误“未知的运行时错误”
【发布时间】:2012-12-09 21:16:36
【问题描述】:

我写了一个代码来从 excel 表中删除行,但它给了我一个主题中提到的错误。

代码

 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

请在下面找到调试屏幕:

你能帮我说说原因吗?

【问题讨论】:

    标签: excel vbscript vba


    【解决方案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
    

    【讨论】:

    • 这种方式删除行,无论如何都可以删除不需要的行,因为删除导致行向上移动对吗?有更快的过程吗?它会一一删除对吗?
    • 好吧,显然你可以把它分成几块......我费心更新以展示一种可能的方式。
    • 不错,只是为了确认一下-是UBOUND(rangesToRemove)还是UBOUND(rangesToRemove)-1
    • 请看你说的修改后的代码,我还是把它弄碎了!但没有改善!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多