VB5, VB6  •  Prepare HTML for the Clipboard

Listing 1. This routine is useful when you build the descriptive header string for an HTML fragment. If you pass an entire HTML document, the StartFragment tag is injected immediately following the <body> tag, and the EndFragment tag immediately before </body>. If you pass a fragment rather than a complete document, the routine makes it minimally whole by the addition of <html> and <body> tag sets. Use the ideas in this routine to construct variations for other scenarios easily.

Public Function HtmlDescribed(ByVal Fragment As _
   String) As String
   Dim Data As String
   Dim nPos As Long
   Const Description As String = _
      "Version:1.0" & vbCrLf & _
      "StartHTML:aaaaaaaaaa" & vbCrLf & _
      "EndHTML:bbbbbbbbbb" & vbCrLf & _
      "StartFragment:cccccccccc" & vbCrLf & _
      "EndFragment:dddddddddd" & vbCrLf
   Const FragmentStart As String = _
      "<!--StartFragment-->"
   Const FragmentEnd As String = _
      "<!--EndFragment-->"
   Const Fmt As String = "0000000000"
   
   ' Add the starting and ending tags for the 
   ' HTML fragment by looking for <body> tag.
   nPos = InStr(1, Fragment, "<body", _
      vbTextCompare)
   Select Case nPos
      Case 0
         Fragment = "<html><body>" & vbCrLf & _
            FragmentStart & Fragment
      Case Else
         nPos = InStr(nPos, Fragment, ">")
         If nPos > 0 And nPos < Len(Fragment) _
            Then
            Fragment = Left$(Fragment, nPos) & _
               FragmentStart & Mid$(Fragment, 
               nPos + 1)
         End If
   End Select
      
   nPos = InStr(1, Fragment, "</body", _
      vbTextCompare)
   Select Case nPos
      Case 0
         Fragment = Fragment & FragmentEnd & _
            vbCrLf & "</body></html>"
      Case Else
         Fragment = Left$(Fragment, nPos - 1) & _
            FragmentEnd & Mid$(Fragment, nPos)
   End Select
   
   ' Build the HTML given the description, the 
   ' fragment, and the context. And, replace the 
   ' offset placeholders in the description with 
   ' values for the offsets of StartHMTL, 
   ' EndHTML, StartFragment, and EndFragment.
   ' Offsets need to be zero-based when placed on 
   ' clipboard, so subtract 1
   ' from each before injecting.
   Data = Description & Fragment
   Data = Replace(Data, "aaaaaaaaaa", _
      Format$(Len(Description), Fmt))
   Data = Replace(Data, "bbbbbbbbbb", _
      Format$(Len(Data), Fmt))
   nPos = InStr(Data, FragmentStart) - 1
   Data = Replace(Data, "cccccccccc", _
      Format$(nPos + Len(FragmentStart), Fmt))
   nPos = InStr(Data, FragmentEnd) - 1
   Data = Replace(Data, "dddddddddd", _
      Format$(nPos, Fmt))
   ' Return attributed string.
   HtmlDescribed = Data
End Function