VBA宏(Excel 2010):运行时错误5

时间:2016-05-23 11:46:14

标签: excel vba excel-vba

我已经制作了一个小宏来删除一长串报告中的几个不需要的字符。我想从字符串中删除HTML标记并遇到意外的运行时错误。

我一直有这个奇怪的运行时错误:

strMatter = Mid(str2010, 1, Len(str2010) - 10)

虽然类似的东西起作用:

b = Mid(a, 1, Len(a) - 10)

不同之处在于上面的行是在“For To Loop”中运行的。从逻辑上讲,我已经尝试了几个可以解决这个问题的事情,似乎我不允许在循环中减少变量。我该如何解决这个问题?

运行任何宏之前的B列:strPlaceholder

宏运行后的B列:str2010

非常欢迎每一个帮助和/或建议!

  

编辑:

     

我已更改For intRow = 2 To 5000

     

For intRow = 2 To 13

     

一切正常。如何以找到最后一行的方式更改脚本?

以下是整个小代码:

    Sub WHYYYY()

Dim strPlaceholder As String
Dim strPhrase As String
Dim str2010 As String
Dim strMatter As String
Dim strStart As String
Dim strEnd As String
Dim intRow As Integer
Dim intChar As Integer
Dim intLen As Integer

For intRow = 2 To 5000

    'Clean Description Column
    strPlaceholder = Cells(intRow, 2).Value
    If Not Trim(Len(strPlaceholder)) = 0 Then
        strPhrase = strPlaceholder
        str2010 = Mid(strPhrase, 63, Len(strPhrase))
        strMatter = Mid(str2010, 1, Len(str2010) - 10)
        Cells(intRow, 2) = str2010  'Should be = strMatter
    End If

    'Clean Legal Responsible Column
    strStart = Cells(intRow, 7).Value
    intLen = Len(strStart)

    For intChar = 1 To intLen
        If Not IsNumeric(Mid(strStart, intChar, 1)) Then
            strEnd = strEnd & Mid(strStart, intChar, 1)
        End If
        Cells(intRow, 7) = strEnd
    Next

    Cells(intRow, 7) = Mid(strEnd, 3, 50)
    strEnd = ""

    'Clean Business Responsible Column
    strStart = Cells(intRow, 8).Value
    intLen = Len(strStart)

    For intChar = 1 To intLen
        If Not IsNumeric(Mid(strStart, intChar, 1)) Then
            strEnd = strEnd & Mid(strStart, intChar, 1)
        End If
        Cells(intRow, 8) = strEnd
    Next

    Cells(intRow, 8) = Mid(strEnd, 3, 50)
    strEnd = ""

Next

End Sub

1 个答案:

答案 0 :(得分:1)

我无法理解此时的问题是否仍然是问题中的问题,仍然是:

我一直有这个奇怪的运行时错误:

strMatter = Mid(str2010, 1, Len(str2010) - 10)

虽然类似的东西起作用:

b = Mid(a, 1, Len(a) - 10)

如果它仍然存在,那么您可以改变“策略”,如下所示

Dim cell As Range

With Worksheets("MySheet") '<~~ replace "MySheet" with your actual sheet name
    With Range(.Cells(2, 2), .Cells(.Rows.Count, 2).End(xlUp)).SpecialCells(xlCellTypeConstants, xlTextValues)
        .Replace What:="*><p>", Replacement:="", LookAt:=xlPart, MatchCase:=False
        .Replace What:="</p></div>*", Replacement:="", LookAt:=xlPart, MatchCase:=False

        For Each cell In .Cells
            ' do other stuff
        Next cell

    End With
End With