Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Concatenate strings more efficiently

VBA How To

Concatenate strings more efficiently

by  taupirho  Posted    (Edited  )

If you need to concatenate serious amounts of text (i.e >100000 bytes) together and you're using the regular & or + VBA concatenation operator you'll find that performance can be increased dramatically by using the little known mid$ statement. Here's what the HELP on mid says:


Replaces a specified number of characters in a Variant (String) variable with characters from another string.

Syntax

Mid(stringvar, start[, length]) = string

The Mid statement syntax has these parts:

Part Description
stringvar Required. Name of string variable to
modify.
start Required; Variant (Long). Character
position in stringvar where the
replacement of text begins.
length Optional; Variant (Long). Number of
characters to replace. If omitted, all of
string is used.
string Required. String expression that replaces
part of stringvar.


Remarks

The number of characters replaced is always less than or equal to the number of characters in stringvar.

So say I have a string variable 'data_block' with 900000 characters in it and I want to concatenate another string with 100000 characters onto it - say 'data_line'. Here's how you do it with mid

' make sure our data_block variable can accommodate 1000000 characters
' and our data_line can take 100000

data_block = String$(1000000, " ")
data_line = String$(100000, " ")

' Assume we've now filled data_block with 900000 characters and data_line with 100000 characters
' We now concatenate them

Offset = len(data_block) + 1
Mid(data_block, Offset ) = data_line


Again for small strings just use the & operator but the speed increase in using mid$ for large string variables is significant.

Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top