I just wrote the following function, but it seems a bit bulky for what it does. When you pass the function a string, a worksheet object, and a row number as arguments, it looks for embedded flags in the string that consist of the "&" character followed by a column letter (ex "&A"
. For each valid flag it finds, it replaces the flag in the string with the contents of the cell specified by the flag's column letter and the row number passed to the function. Clear as mud?
If someone could help me optimize this, I'd sure appreciate it!
Thanks,
VBAjedi![[swords] [swords] [swords]](/data/assets/smilies/swords.gif)
If someone could help me optimize this, I'd sure appreciate it!
Code:
Function MergeColVals(TemplateString As String, DataSheet As Worksheet, DataRow As Integer)
Dim x, y, a
Dim MkrPos
Dim TmpStr$, FieldVal$, ColLtr$
Dim LeftString$, RightString$
x = 1
TmpStr = TemplateString
Do While x < Len(TmpStr) And x > 0
MkrPos = InStr(x, TmpStr, "&")
If Not MkrPos = 0 Then ' & character found at pos. MkrPos
' Extract flag's column letter, get field value if flag valid
x = MkrPos + 1 ' On next loop, look for & starting at following character
ColLtr = ""
For y = 1 To 2 ' Possible columns from "A" to "IV"
a = UCase(Mid(TmpStr, MkrPos + y, 1)) ' Ucase adjusts for $Ab, etc.
Select Case a
Case "A" To "Z"
ColLtr = ColLtr & a
Case Else
Exit For ' space or punctuation marks end of flag
End Select
Next y
If Len(ColLtr) > 0 Then ' Valid marker found
FieldVal = DataSheet.Range(ColLtr & DataRow).Value
FlagLength = Len(ColLtr) + 1 ' account for & too. . .
Else
FieldVal = ""
FlagLength = 0 ' Leave & intact, it's not a flag
End If
LeftString = Left(TmpStr, (MkrPos - 1))
RightString = Right(TmpStr, Len(TmpStr) - (MkrPos - 1 + FlagLength))
TmpStr = LeftString & FieldVal & RightString
Else
x = 0 ' no more & characters in string
End If
Loop
MergeColVals = TmpStr
End Function
Sub TestFunct()
' Put test values in Sheet1 cells A8 and AA8
Dim x
x = MergeColVals("Simple &A Test & Value &aa.", Sheet1, 8)
MsgBox x
End Sub
Thanks,
VBAjedi
![[swords] [swords] [swords]](/data/assets/smilies/swords.gif)