Question

I use the following sub extensively in an excel based application that I'm building. It either prints out the value that is passed to it, or passes the value along to another function if it's too long to fit in a cell.

Sub printValue(ws As Worksheet, row As Long, column As Long, value As String)
    If Len(value) > 32767 Then
        printOverflowString ws, row, column, value
    Else
        ws.Cells(row, column).value = value
    End If
End Sub

The problem is that sometimes, with no pattern, no rhyme, and no reason, it throws an application-defined or object defined error on the line

ws.Cells(row, column).value = value

This happens most frequently when processing twitter posts, and the types of strings that tend to break it look suspiciously like injection attacks. Here's an example:

Watch :   :         Value : "=Lady Gaga vs Demi Lovato, Whos Right In the Vomit War? http://t.co/lx9FbKhUYv" : String : Tools.printValue

So clearly I need to sanitize the string a bit more, but I don't really know how to go about doing that. Stripping out all the punctuation isn't an option, and i need the print function to still be as snappy as is possible.

Any pointing in the right direction wold be of great help!

Was it helpful?

Solution

Using your code, I was unable to recreate the problem with your example (I had it perform the subroutine 1,000 times). For clarification, you are not 'printing' a value, you are just placing in a cell. If the problem occurs LATER when you try to print, then that's a whole different story / solution. You have a couple of options: (1) If truly just random, then try the subroutine again; (2) Or try and figure out what character(s) or combination is causing the issue. The following code places an error trap in your subroutine, then just retries the command five times. If you find that 'hides' your problem, then good. If you get the message box, then you could add code to strip out some character(s) and retry.

P.S. It is a really bad idea to name variables using reserved words. You use row, column, value; I would use lRow, lCol, strValue.

Sub printValue(ws As Worksheet, row As Long, column As Long, value As String)
    Dim iRetryCount     As Integer
    On Error GoTo Error_Trap
    iRetryCount = 5
    If Len(value) > 32767 Then
        printOverflowString ws, row, column, value
    Else
        ws.Cells(row, column).value = value
    End If
    Exit Sub
Error_Trap:
    Debug.Print Err.Number & vbTab & Err.Description
    iRetryCount = iRetryCount - 1
    If iRetryCount = 0 Then
        MsgBox "Add some code to figure out what the cause is", vbOKOnly, "Still Getting Error"
        Exit Sub
    Else
        DoEvents
        Resume
    End If
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top