Function to insert text adding a carriage return for some reason

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Seth Schrock
    Recognized Expert Specialist
    • Dec 2010
    • 2965

    Function to insert text adding a carriage return for some reason

    I found a function online that finds the cursor in a textbox, and then allows me to insert a string where the cursor is. When I call it as the website suggested, it works fine. However, it selects the whole field. I added a part that makes it so that it finds where the cursor was + the length of the added string and sets the .SelStart to this value. However, when I try to use this added ability, it adds a carriage return at my .SelStart point. I can't figure out what is happening.

    Here is the original way that I called the function:
    Code:
    LegalWording = ReplaceViaPosition(Me.LegalWording.Text, gCursorPosition, gCursorLen, "%year%", True)
    Here is the way that adds the carriage return:
    Code:
    With Me.LegalWording
                    .SetFocus
                    LegalWording = ReplaceViaPosition(.Text, gCursorPosition, gCursorLen, "%month%", False)
                    .SelStart = intNextStart
                End With
    Interesting note: If i comment out the line .SelStart = intNextStart, then it wipes out the entire string that was in the textbox (Me.LegalWordin g), inserts the carriage return and does not add the string that I wanted to add.

    Here is the entire ReplaceViaPosit ion() function:
    Code:
    Public intNextStart As Integer
    ' ARGUMENTS:
    ' *strText: The original text to modify
    ' *intStart: The start position to enter or replace text (0 based)
    ' *intLen: The length of the selection to replace (0 based) (default 0)
    ' *strAdd: The text to add to the string (default ZLS)
    ' *bPadAddition: True to pad the added text with a space (default False)
    ' * * * * * * * *If the addition is at the start of the string no leading
    ' * * * * * * * *space will be added.
    ' * * * * * * * *If the padding results in two consecutive spaces the
    ' * * * * * * * *consecutive space will be removed
    ' * * * * * * * *Padding operations will be bypassed if strAdd is a ZLS
    
    Public Function ReplaceViaPosition( _
       ByVal strText As String, _
       intStart As Integer, _
       Optional intLen As Integer = 0, _
       Optional strAdd As String = "", _
       Optional bPadAddition As Boolean = False _
       ) As String
    On Error GoTo Error_Proc
    Dim Ret As String
    '=========================
     Dim strOriginal As String
    '=========================
    
     'retain the original in case of error
     strOriginal = strText
    
     'set the value of where the cursor should be after the inserted text
     intNextStart = intStart + Len(strAdd)
    
     'validate the position and length to make sure
     'they're within an appropriate range
     If ((intStart) > Len(strText)) Or _
        (intStart + intLen) > Len(strText) Then
       'bad entry, let's raise error 9: Subscript out of range
       Err.Raise 9, "ReplaceViaPosition", "Subscript out of range"
     End If
    
     'remove any text that is selected due to intLen
     If intLen > 0 Then
       strText = Left(strText, intStart) & Mid(strText, intStart + intLen + 1)
     End If
     
     If Len(strAdd) <> 0 Then
       'add strAdd to the string in the specified position
       strText = Left(strText, intStart) & strAdd & Mid(strText, intStart + 1)
       
       'perform the padding if required
       If bPadAddition Then
       
         'work on the leading space first
         
         'if we're adding to the start of the string we don't need
         'any leading spaces
         If intStart > 0 Then
           'find out if the char before the addition is a space
           If Mid(strText, intStart, 1) <> " " Then
             'it's not a space, we'll need to enter one
             strText = Left(strText, intStart) & " " & Mid(strText, intStart + 1)
             'we added a space, so let's increase our intStart by one
             'to compensate for the next check
             intStart = intStart + 1
             'increase intNextStart by 1 to account for the added space
             intNextStart = intNextStart + 1
           End If
         End If
       
         'work on the trailing space next
       
         'find out if the char after the addition is a space
         If Mid(strText, intStart + 1 + Len(strAdd), 1) <> " " Then
           'it's not a space, we'll need to enter one
           'but first check if it's the end of the text...
           If (intStart + Len(strAdd)) < Len(strText) Then
             'ok, we're safe to add a space after the addition
             strText = Left(strText, intStart + Len(strAdd)) & " " & Mid(strText, intStart + Len(strAdd) + 1)
             'increase intNextStart by 1 to account for the added space
             intNextStart = intNextStart + 1
           End If
         End If
    
       End If
       
     End If
     
     Ret = strText
    
    '=========================
    Exit_Proc:
     ReplaceViaPosition = Ret
     Exit Function
    Error_Proc:
     Ret = strOriginal
     MsgBox "Error: " & Trim(Str(Err.Number)) & vbCrLf & _
       "Desc: " & Err.Description & vbCrLf & vbCrLf & _
       "Module: modReplaceViaPosition, Procedure: ReplaceViaPosition" _
       , vbCritical, "Error!"
     Resume Exit_Proc
     Resume
    End Function
    I added lines #19 & 20, 54 & 55, and 68 & 69 so that I could then set the cursor at the end of the inserted text.
    Here is the link to the website where I found this function: ReplaceViaPosit ion

    The function obviously works as it works when just performing its original purpose, so I don't think that the function is the problem (I could be wrong). I think that there is something about the way that I call the function my way that throws it for a loop.

    gCursorPosition and gCursorLen are declared as integers.
  • TheSmileyCoder
    Recognized Expert Moderator Top Contributor
    • Dec 2009
    • 2322

    #2
    I don't see anything that would add a carriage return, in what you have posted. The function code, is that the original or your modified version?

    Comment

    • Seth Schrock
      Recognized Expert Specialist
      • Dec 2010
      • 2965

      #3
      The function code is my slightly edit version. The lines that I added are lines 19-20, 54-55, and 68-69. I looked through as well and couldn't find anything either. However, I'm very unfamiliar with the Left() and Mid() functions and all the properties that were used in them, so I couldn't be sure.

      I've actually just finished creating my own function to do this and it works fine. The main difference that I see is that I did my .SelStart inside the insertBlank procedure instead of in the calling procedure. Not sure why that would make a difference. Here is what I created:
      Code:
      Public Sub insertBlank1(strText As String, intStart As Integer, intLen As Integer, _
                              strAddition As String, Optional blnSpaceCheck As Boolean = False)
                              
      Dim strLeft As String
      Dim strRight As String
      Dim strFinal As String
      
      
      '**************************************
      'Grab text to the left of the selection
      '**************************************
      
      'Check if the selection starts at the beginning of the textbox
      If intStart = 0 Then
          strLeft = ""
      Else
          strLeft = Left(strText, intStart)
      End If
      
      
      '***************************************
      'Grab text to the right of the selection
      '***************************************
      
      'Check if the selection ends at the end of the string
      If (intStart + intLen) = Len(strText) Then
          strRight = ""
      Else
          strRight = Mid(strText, intStart + intLen + 1)
      End If
      
      
      '****************************************************
      'Checking for spaces around where strAddition will go
      '****************************************************
      
      If blnSpaceCheck = True Then
          
          'If strLeft = "" then strAddition will go at the beginning
          'of the textbox and doesn't need a preceding space
          If strLeft <> "" Then
              
              'Check if there is a space at the end of the string
              If Right(strLeft, 1) <> " " Then
                  strLeft = strLeft & " "
              End If
          
          
          End If
      
      
          'If strRight = "" then strAddition will go at the end
          'of the textbox and doesn't need a proceding space
          If strRight <> "" Then
              
              'Check if there is a space at the beginning of the string
              If Left(strRight, 1) <> " " Then
                  strRight = " " & strRight
              End If
              
          End If
      
      End If
      
      strFinal = strLeft & strAddition & strRight
      
      With Forms!frmPenalCodes!LegalWording
          .SetFocus
          .Value = strFinal
          .SelStart = Len(strLeft) + Len(strAddition)
      End With
      
      End Sub
      Personally, I think mine is clearer than theirs, but I might be a little biased :)

      Comment

      • zmbd
        Recognized Expert Moderator Expert
        • Mar 2012
        • 5501

        #4
        Seth,
        I'm with Rabbit, there isn't anything obvious that should be doing this...

        So, to my next tool in the bag-o-tricks:

        Are you familiar with the watch window?
        This is like the coolest... often better than the locals window.

        Here's what I do when strange things happen and I just can't seem to track them down with the usual methods.
        Open the VBA editor.
        Find the variable that I'm trying to track...
        Select
        <shift><F9>
        This should open the watch window and add the variable to that window.
        I do this for each variable of interest (this is a great tool for trouble shooting code when all seems lost... there are other options too - in the VBE ribbon goto debug, add watch, [Help])
        Now add a stop before the weirdness begins.
        [F8]
        And you can watch how things are progressing.

        Comment

        • Seth Schrock
          Recognized Expert Specialist
          • Dec 2010
          • 2965

          #5
          I think that I have reached the ultimate in weirdness. If I place a stop at the very beginning of the function (line 26 of the OP to be exact) and watch strText, the function works beautifully. If I then remove the Stop, it goes back to adding the carriage return. Do you have anything in your bag of tricks for this?

          I think that I'm going to stick with the function that I created (post #3). I think it is much more clear of what is going on and easier to read than the one I found online.

          Comment

          • NeoPa
            Recognized Expert Moderator MVP
            • Oct 2006
            • 32653

            #6
            That happens sometimes Seth. A bitch really, but there you go.

            The trick there is to go old-school and get the code to log the values as they are changed. This allows the code to run in real-time. It also shows exactly what does what and where in your code. The The Immediate Pane (Ctrl-G) is where your results should be printed to. It may be slow and laborious, but it is a way to debug that isn't exposed to that real-time problem found when tracing through some code.

            Comment

            • zmbd
              Recognized Expert Moderator Expert
              • Mar 2012
              • 5501

              #7
              NeoPa beat me to the punch... been very busy with family events.
              Yes, that stupid CR shows up. I've even had an occasion where there were spaces between letters ("wantedthistex t" and "w a n t e d t h i s t e x t" is what I got!) didn't show up in the watch-window, only at run-time, turned out to be an interference from one of the IT "watch-dog" programs because this didn't happen at home.

              Comment

              Working...