I am new in Macro VBA and I am facing a problem.
I having two string to compare, and how do I get the string as Result shown if the similarity numbers found in both string?
string 1 : 1,2,3,4,6,7,8,9,10,11,12,13,19,20
string 2 : 2,3,7,8,9,10,11
After comparison:
Result : 2,3,7,8,9,10,11
Code:
If ActiveSheet.Cells(irow + 1, 12).Value = "" Then
'MsgBox "Data not found"
Else
temp = vbNullString
temp = ActiveSheet.Cells(irow + 1, 12).Value
'expanddata() use to expend a sequence of numbers into a display string as below
' 1,2-4,6 -> 1,2,3,4,6
temp = expanddata(temp)
If Worksheets("AI").Cells(irow + 1, 10).Value = temp Then
temp = ConvNum(temp) 'if whole string same then convert back to 1,2-4,6
Else
'the comparision make in here
End If
Worksheets("AI").Cells(irow + 1, 10) = temp
End If
Thank you.
Automating powershell to print the list to a text file c:\temp\test.txt
Sub Test()
a = "(1,2,3,4,6,7,8,9,10,11,12,13,19,20)"
b = "(2,3,7,8,9,10,11)"
cmd = Shell("powershell.exe """ & a & """ | Where {""" & b & """ -Contains $_} | out-file c:\temp\test.txt", 1)
End Sub
For irow = 1 To numofrow
ptcolno = 12
If ActiveSheet.Cells(irow + 1, 12).Value = "" Then
'MsgBox "Data not found"
Else
temp = vbNullString
temp = ActiveSheet.Cells(irow + 1, 12).Value
temp = expanddata(temp)
If Worksheets("AI").Cells(irow + 1, 10).Value = temp Then
temp = ConvNum(temp)
Else
' Answer
Temp2 = Worksheets("AI").Cells(irow + 1, 10).Value
arr1 = Split(Temp2, ",")
arr2 = Split(temp, ",")
temp = vbNullString
For i = LBound(arr2) To UBound(arr2)
For j = LBound(arr1) To UBound(arr1)
If arr2(i) = arr1(j) Then
temp = temp & "," & arr2(i)
End If
Next j
Next i
temp = Right(temp, Len(temp) - 1)
temp = ConvNum(temp)
' End
End If
Worksheets(checktype & "_BUYOFF_1").Cells(irow + 1, 68) = temp
Please try the below code.
Sub comparestring()
string1 = "1,2,3,4,6,7,8,9,10,11,12,13,19,20"
string2 = "2,3,7,8,9,10,11"
str1 = Split(string1, ",")
str2 = Split(string2, ",")
For i = 0 To UBound(str1)
For j = 0 To UBound(str2)
If str1(i) = str2(j) Then
If matchedcontent <> "" Then
matchedcontent = matchedcontent & "," & str1(i)
Else
matchedcontent = str1(i)
End If
End If
Next j
Next i
Range("A3").Value = matchedcontent
End Sub
Assign the two strings to string 1 and string 2 like below results will be printed at Cells A3
string1=Activesheet.Range("A1").Value
string2=Activesheet.Range("A2").Value
try this
Option Explicit
Function CompareStrings(string1 As String, string2 As String) As String
Dim s As Variant
For Each s In Split(string1, ",")
If "," & string2 & "," Like "*," & s & ",*" Then CompareStrings = CompareStrings & s & ","
Next s
CompareStrings = Left(CompareStrings, Len(CompareStrings) - 1)
End Function
which could be called as follows
Sub main()
Dim string1 As String, string2 As String, stringRes As String
string1 = "1,2,3,4,6,7,8,9,10,11,12,13,19,20"
string2 = "2,3,7,8,9,10,11"
stringRes = CompareStrings(string1, string2)
MsgBox stringRes
End Sub
Related
I'm getting a type mismatch in the Dlookup below. Note: the ID column in the Results2 Table is formatted as a Number.
If DLookup("[Result" & i & "]", "Results2", "[ID] = '" & newid & "'") <> Me.Controls("C" & 3 + column & "R" & i + j).Value Then
I've tried changing the newid from a string to an Integer or a Long, but I still get this error.
Full code for this Sub below, if more info is needed.
Private Sub BtnSave_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim rs3 As DAO.Recordset
Dim i As Integer
Dim j As Integer
Dim ans As Integer
Dim column As Integer
Dim colcnt As Integer
Dim newid As String
If IsNull(Me.Spindle3.Value) = False Then
colcnt = 3
ElseIf IsNull(Me.Spindle2.Value) = False Then
colcnt = 2
Else
colcnt = 1
End If
column = 1
Set db = CurrentDb
Set rs = db.OpenRecordset("Results")
Set rs2 = db.OpenRecordset("Results2")
Set rs3 = db.OpenRecordset("Results3")
Linestart:
j = 0
rs.AddNew
newid = rs![ID].Value
If Me.Result1.Value = "Fail" Or Me.Result2.Value = "Fail" Or Me.Result1.Value = "Fail" Then
If column = 1 Then
ans = MsgBox("This is a FAILING Result. Do you with to save it?", vbYesNo)
If ans = 7 Then GoTo Lineend
End If
ElseIf Me.Result1.Value = "Incomplete" Or Me.Result2.Value = "Incomplete" Or Me.Result2.Value = "Incomplete" Then
If column = 1 Then
ans = MsgBox("Testing is not finished for this part. Do you with to save and close now?", vbYesNo)
If ans = 7 Then GoTo Lineend
End If
End If
With rs
![PartNum] = Me.FilterPartNumber.Value
![INDNum] = Me.INDNum.Value
![DateTime] = Me.DateTime.Value
![HTLotNum] = Me.HTLotNum.Value
![Operator] = Me.Inspector.Value
![Spindle] = Me.Controls("Spindle" & column).Value
![TypeofCheck] = Me.InspType.Value
![OverallResult] = Me.Controls("Result" & column).Value
End With
rs2.AddNew
With rs2
![ID] = newid
![PartNum] = Me.FilterPartNumber.Value
![Plant] = Me.plantnum.Value
![DateTime] = Me.DateTime.Value
![HTLotNum] = Me.HTLotNum.Value
![Notes] = Me.Notes.Value
![Spindle] = Me.Spindle.Value
![TypeofCheck] = Me.InspType.Value
![OverallResult] = Me.Result1.Value
End With
rs3.AddNew
With rs3
![ID] = newid
![PartNum] = Me.FilterPartNumber.Value
![DateTime] = Me.DateTime.Value
End With
If IsNull(Me.HTLotNum.Value) = True Then
rs![HTLotNum] = "(blank)"
rs![HTLotNum] = "(blank)"
End If
For i = 1 To 90 Step 1
If i + j >= 90 Then
i = 90
GoTo Line1
End If
If IsNull(Me.Controls("C3R" & i + j).Value) = True Then
j = j + 1
End If
If i + j >= 90 Then
i = 90
GoTo Line1
End If
If IsNull(Me.Controls("C2R" & i + j).Value) = True Then GoTo Line1
rs("Char" & i) = Me!ListFeatures.column(1, i - 1)
rs("Desc" & i) = Me!ListFeatures.column(2, i - 1)
rs("Spec" & i) = Me!ListFeatures.column(3, i - 1) & " " & Me!ListFeatures.column(6, i - 1)
rs2("SC" & i) = Me!ListFeatures.column(4, i - 1)
rs2("Location" & i) = Me!ListFeatures.column(5, i - 1)
rs2("Result" & i) = Me.Controls("C" & 3 + column & "R" & i + j).Value
rs3("Coding" & i) = Me!ListCoding.column(1, i - 1)
Line1:
Next
rs.Update
rs2.Update
rs3.Update
For i = 1 To 90 Step 1
If i + j >= 90 Then
i = 90
GoTo Line1
End If
If IsNull(Me.Controls("C3R" & i + j).Value) = True Then
j = j + 1
End If
If i + j >= 90 Then
i = 90
GoTo Line1
End If
If DLookup("[Result" & i & "]", "Results2", "[ID] = '" & newid & "'") <> Me.Controls("C" & 3 + column & "R" & i + j).Value Then
MsgBox "Results not saved! Document results on paper and contact the database engineer regarding this error."
GoTo Lineend:
End If
Next
If column < colcnt Then
column = column + 1
GoTo Linestart
End If
Line2:
Forms![Landing Page]![LIstIncomplete].Requery
DoCmd.Close
Lineend:
End Sub
Per one of the comments, I updated the trouble line to the line below. I'm almost certain that was how I initially wrote this line and added the apostrophes as an attempt to fix.
If DLookup("[Result" & i & "]", "Results2", "[ID] = " & newid) <> Me.Controls("C" & 3 + column & "R" & i + j).Value Then
I had to fix one of my Goto's as well, one of them led to an infinite loop, but now everything is working as intended.
Thanks for the help!
I need to import into Access table this EDI text file ( ' as line terminator):
UNA:+.?'
UNB+UNOC:3+BRANDEUROPE+ANYCODE+180206:1121+5439'
UNH+5439-1+DESADV:D:99B:UN'
BGM+351+0089430043+9'
DTM+11:20180205:102'
DTM+137:20180205:102'
MEA+WT+AAD+KGM:2126.100'
MEA+CT+SQ+NMP:00000'
NAD+DP+0017309707++NameStreet 22+Rome++00100+IT'
CTA+DL'
NAD+SU+DE++BRAND Systems+Rome+Rome++00100+IT'
CTA+DL'
TOD+6++CIP'
CPS+1'
PAC+2++BX'
MEA+WT+G+KGM:88'
PCI+24'
GIN+ML+AL7B009435+AL7B009438'
LIN+1++46550705:VP'
PIA+1+4114793:BP'
IMD+A++:::C833dn-EURO'
QTY+12:2'
RFF+OP:44CKV07S:000001'
CPS+2'
PAC+1++BX'
MEA+WT+G+KGM:0.01'
PCI+24'
LIN+1++01182907:VP'
PIA+1+4113617:BP'
IMD+A++:::RAM-256MB-C3/C5/C6/C7/MC3/MC5/C8'
QTY+12:1'
RFF+OP:44CKV07S:000003'
CPS+3'
PAC+4++BX'
MEA+WT+G+KGM:43.2'
PCI+24'
LIN+1++46361802:VP'
PIA+1+4114805:BP'
IMD+A++:::Tray-C5x2/MC5x3'
QTY+12:4'
RFF+OP:44CKV07S:000006'
This is the result I need:
0089430043 05/02/2018 46550705 AL7B009435
0089430043 05/02/2018 46550705 AL7B009438
etc...
and this is what I tried:
Public Function import1()
Dim strFilename As String: strFilename = "C:\despatch.txt"
Dim strTextLine, CodProd, DataDoc As String
Dim SNarray() As String
Dim NumDoc As Long
Dim nPAC, NumRig, intCount As Integer
Dim iFile As Integer: iFile = FreeFile
Open strFilename For Input As #iFile
Do Until EOF(1)
Line Input #1, strTextLine
strTextLine = Replace(strTextLine, "'", "")
'BGM
If Left(strTextLine, 3) = "BGM" Then
NumDoc = Mid(strTextLine, 9, 10)
End If
'DTM
If Left(strTextLine, 6) = "DTM+11" Then
DataDoc = Mid(strTextLine, 14, 2) & "/" & Mid(strTextLine, 12, 2) & "/" & Mid(strTextLine, 8, 4)
End If
'CPS = numero record
If Left(strTextLine, 3) = "CPS" Then
NumRig = Val(Mid(strTextLine, 5, 3))
End If
'PAC = numero di matricole da estrarre
If Left(strTextLine, 3) = "PAC" Then
nPAC = Val(Mid(strTextLine, 5, 3))
End If
'GIN
If Left(strTextLine, 3) = "GIN" Then
'strTextLine.MoveNext
End If
'LIN
If Left(strTextLine, 3) = "LIN" Then
CodProd = Mid(strTextLine, 8, 8)
End If
'strTextLine.MovePrevious
SNarray = Split(Mid(strTextLine, 8), "+")
For intCount = LBound(SNarray) To UBound(SNarray)
Debug.Print NumDoc & " " & DataDoc & " " & NumRig & " " & CodProd & " " & SNarray(intCount)
Next
'strTextLine.MovePrevious
'strTextLine.MovePrevious
Loop
Close #iFile
End Function
Before to import GIN record with serial numbers, I need to achieve the LIN record with che product code, and then pass them to variables.
I've tried with .MoveNext and then with two .MovePrevious but it gives me error: object needed.
Any help would be appreciated.
Thanks.
This is an example of a function that parses an EDIFACT segment, it's not debugged but it shows the algorithm to read the EDI data. It can be easily adapted to read ANSI X12.
Function GetLine() as String()
Dim Elements as String(99,3)
Do Until EOF(1)
mychar = Input(1, #1) ' Get one character
If mychar = vbCr Or \
mychar = vbLf Then ' Skip Line Breaks
Continue
Else If mychar = "?" Then ' Process Escape
If EOF(1) Then Exit Do ' Reached end of file
mychar = Input(1, #1)
data = data & mychar ' Treat next char as regular
Else If mychar = "'" Then ' End of Segment
Exit Do
Else If mychar = "+" Then ' Element separator
Elements(Elem,Comp) = data
data = ""
Comp = 1
Elem = Elem + 1
Else If mychar = ":" Then ' Composite separator
Elements(Elem,Comp) = data
data = ""
Comp = Comp + 1
Else ' Regular data
data = data & mychar
End If
Loop
Elements(Elem,Comp) = data
GetLine = Elements
End Function
Example use
'BGM
If Elements(0,0) = "BGM" Then
NumDoc = Elements(2,1)
End If
Finally I solved (I really don't know how I did), here my code:
Function GetLine() As String()
Dim FSO As Object, objFile, objFolderIN, objFolderOUT As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objFolderIN = FSO.GetFolder("C:\IN")
Set objFolderOUT = FSO.GetFolder("C:\Archivio")
Dim data, elem, comp
Dim i As Integer
Dim iFile As Integer: iFile = FreeFile
Dim Elements(99, 3) As String
Dim mychar As String
Dim NumDoc As Long
i = 1
For Each objFile In objFolderIN.Files
Open objFile For Input As #iFile
Do Until EOF(1)
Line Input #1, data
'Debug.Print data
mychar = Input(1, #1) ' Get one character.
If mychar = "'" Then Exit Do ' End of Segment
If mychar = vbCr Or _
mychar = vbLf Then
'Continue
ElseIf mychar = "?" Then
mychar = Input(1, #1) ' Skip Line Breaks and Escape
data = data & mychar
ElseIf mychar = "'" Then
Exit Do
ElseIf mychar = "+" Then ' Element separator
Elements(elem, comp) = data
data = ""
comp = 1
elem = elem + 1
ElseIf mychar = ":" Then ' Composite separator
Elements(elem, comp) = data
data = ""
comp = comp + 1
Else ' Regular data
data = data & mychar
End If
Loop
Elements(elem, comp) = data
GetLine = Elements
Close #iFile
i = i + 1
Next objFile
'BGM
If Elements(0, 0) = "BGM" Then
NumDoc = Elements(2, 1)
Debug.Print NumDoc
End If
End Function
I have following data in cell A1 -
EP10101010 | EP202020 | EP300005 | US789456 | US876543 | NZ90876 | LP98789 | LP88888
I want values that are starting with the same characters (e.g. EP) to be separated and grouped in one cell.
Desired output:
Cell A2 - EP10101010 | EP202020 | EP300005
Cell A3 - US789456 | US876543
Cell A4 - NZ90876
Cell A5 - LP98789 | LP88888
you could try this:
Sub main()
Dim strng As Variant, strngs As Variant
Dim lastStrngID As String, resStrng As String
Dim rowIndex As Long
strngs = Split(Replace(Range("A1"), " ", ""), "|")
rowIndex = 2
lastStrngID = Left(strngs(0), 2)
For Each strng In strngs
If Left(strng, 2) <> lastStrngID Then
Cells(rowIndex, 1).Value = Left(resStrng, Len(resStrng) - 1)
rowIndex = rowIndex + 1
lastStrngID = Left(strng, 2)
resStrng = strng & " | "
Else
resStrng = resStrng & strng & "|"
End If
Next
Cells(rowIndex, 1).Value = Left(resStrng, Len(resStrng) - 1)
End Sub
or, alternatively:
Sub main2()
Dim strng As Variant
With CreateObject("Scripting.Dictionary")
For Each strng In Split(Replace(Range("A1"), " ", ""), "|")
.Item(Left(strng, 2)) = .Item(Left(strng, 2)) & "|" & strng & "|"
Next
Range("A2").Resize(.count).Value = Application.Transpose(.Items)
With Range("A2").Resize(.count)
.Replace "||", "--"
.Replace "|", ""
.Replace "--", " | "
End With
End With
End Sub
I've got this code:
Public Function SplitStart(start As String, text As String) As String
Dim splitString() As String
Dim st As Variant
Dim returnstring As String
Dim i As Integer
Dim trimmed As String
splitString = Split(text, " | ")
returnstring = ""
For Each st In splitString
trimmed = Trim(st)
If Left(trimmed, Len(start)) = start Then
If returnstring <> "" Then
returnstring = returnstring + " | "
End If
returnstring = returnstring + trimmed
End If
Next
SplitStart = returnstring
End Function
You insert it into a module and then you can use
=splitstart("EP";A1)
For example in A2
I'm currently using the below code in a VB.Net console app that takes the contents of a text file and extracts certain info and then exports it to a CSV.
All seems to work well but the problem is the file originally comes through as a PDF (only option possible) and i have to manually open the file in Adobe and 'Save as Text'.
Is there a way of either automating the conversion of PDF to text file or reading the PDF in place of the text file.
Any guidance or options would be appreciated
Dim iLine, iEnd, c, iField As Integer
Dim iSecs, iMax As Long
Dim sText, sTemp, sSchema As String
Dim sHotel, sEndDate, sMon, sPLU, sTots, sValue, sDept, sFile, sOutFile, sDesc As String
Dim tdate As Date
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\temp\TX.accdb;")
Dim LUse As Boolean
sHotel = "Unknown Hotel"
sEndDate = "01/01/2015"
sMon = "MAR"
sPLU = ""
sTots = "0"
sValue = "0"
sDept = "Unknown Dept"
sDesc = ""
LUse = True
sTemp = ""
iField = 0
sSchema = "Chester"
'Open input file
sFile = "c:\temp\input.txt"
Dim InFile As New System.IO.StreamReader(sFile)
'Open lookup data table
con.Open()
Dim dbAdapter As OleDbDataAdapter = New OleDbDataAdapter( _
"SELECT * FROM Plookup", con)
Dim dsTX As DataSet = New DataSet()
Dim changes As DataTable
Dim cmdbuilder As OleDbCommandBuilder = New OleDbCommandBuilder(dbAdapter)
dbAdapter.FillSchema(dsTX, SchemaType.Source, "Plookup")
dbAdapter.Fill(dsTX, "Plookup")
Dim rstx As DataTable = dsTX.Tables(0)
iMax = rstx.Rows.Count
Dim productrow() As Data.DataRow
'Open Output file
iSecs = Timer
sOutFile = "c:\temp\TX" & Format$(Now, "yymmdd") & Trim$(Str$(iSecs)) & ".csv"
FileCopy(sFile, "c:\temp\TX" & Format$(Now, "yymmdd") & Trim$(Str$(iSecs)) & ".txt")
Dim OutFile As New System.IO.StreamWriter(sOutFile)
'Write header
OutFile.WriteLine("outlet,dept,epos,tots sold,total price,date of sales")
iLine = 0
Do While InFile.Peek() <> -1
'Read in text
iLine = iLine + 1
sText = InFile.ReadLine
sText = sText.Replace(",", "")
If Len(sText) > 2 And Len(sText) < 9 Then
If Mid$(sText, 3, 1) = "-" Then ' Department Name
sText = sText & Space(9 - Len(sText))
End If
End If
'Process all rows except header row - read data into array
If Len(sText) > 8 Then
Select Case Left(sText, 7)
Case "Consoli" ' Ignore
Case "Quanti " ' Ignore
Case "Group b" ' Ignore - but next row is the Hotel Name
iLine = iLine + 1
sText = InFile.ReadLine
sText = sText.Replace(",", "")
sHotel = Trim$(Left(sText, 20)) 'The username follows so we may truncate the hotel name
Case "Date ra" ' End date
sEndDate = Mid$(sText, 29, 2) & "/" & Mid$(sText, 32, 2) & "/" & Mid$(sText, 35, 4)
tdate = CDate(sEndDate).AddDays(-1)
sEndDate = tdate.ToString("dd/MM/yyyy")
Case Else 'Possible Code
If Mid$(sText, 3, 1) = "-" Then ' Department Name
sDept = Trim(sText)
Else
If IsNumeric(Left(sText, 7)) Then 'Got a code
sPLU = Trim(Str(Val(Left(sText, 7))))
'We don't know where the description ends as it contains spaces
'So best way is to start at the end and work back...
iEnd = Len(sText)
iField = 0
For c = iEnd To 9 Step -1
If Not (Mid(sText, c, 1) = " ") Or iField > 10 Then
sTemp = Mid(sText, c, 1) & sTemp
Else
iField = iField + 1
If iField = 9 Then
sValue = sTemp
ElseIf iField = 11 Then
sTots = sTemp
End If
sTemp = ""
End If
Next
If iField = 10 Then
sTots = Trim(sTemp)
sDesc = ""
Else
sDesc = Trim$(sTemp)
End If
'lookup code
productrow = rstx.Select("FileID = 'Chester' and PLU = '" & sPLU & "'")
If productrow.Length = 0 Then ' product not found
iMax = iMax + 1
rstx.Rows.Add(sSchema, sPLU, sDesc, False)
LUse = True
Else
LUse = Not productrow(0)("Exclude")
End If
If (Val(sTots) + Val(sValue) > 0) And LUse Then ' We have a non-zero sale or value and it is not excluded
OutFile.WriteLine(sHotel & "," & sDept & "," & sPLU & "," & sTots & "," & sValue & "," & sEndDate)
End If
End If
End If
End Select
End If
Loop
'dbAdapter.Update(dsTX.Tables(0))
'Close input / output csv files
'rstx.Rows.Add("303030", "Another Test", False)
dbAdapter.UpdateCommand = cmdbuilder.GetUpdateCommand(True)
dbAdapter.InsertCommand = cmdbuilder.GetInsertCommand(True)
dbAdapter.DeleteCommand = cmdbuilder.GetDeleteCommand()
changes = rstx.GetChanges()
If changes IsNot Nothing Then dbAdapter.Update(changes)
InFile.Close()
OutFile.Close()
con.Close()
Try itextSharp. itextSharp is a .NET DLL with the help of which you can extract content from PDF. Click here for reference & sample code(although code is in c#, its just a reference to give you an idea).
I'm a graphic artist, new to Excel and VBA but trying to use it to process mountains of data in excel to be used as variable data in Illustrator.
If I want to convert cells with product names for signs like "Budwieser, Bud Light & Bud Black Crown" to an abbreviation following the format "Budweiser_BL_BBC"
I have written a function that I thought would accomplish my task but it returns #VALUE!
Edit
To explain the logic: my idea was to take the string, split it on " & " and then split the first position of the resulting array on ", " then adding what was after the "&" to the end of the second array - this array, sProd, has the products separated into different positions of the array.
Then looping through that array and splitting each product at the spaces creating a jagged array.
Then loop through that array again creating a string taking only the first letter of each word in each product, separating products with an underscore. The exception being that the first word of the first product is spelled out and set in proper case. (Just saw an error in my logic and added the code for the first word exception).
Edit #2
The function should return a string with the first word of the original string set in proper case with all other words abbreviated to their first letter and products separated by underscores. So "Budweiser, Bud Light & Bud Light Lime" returns "Budweiser_BL_BLL", "All Coke & Dr Pepper Products" would return "AllC_DPP" and "Gatorade" returns "Gatorade".
This is my first bout with Excel and VBA.
Function Abbrev(p As String) As String
Dim sAmpersand() As Variant
Dim sProd() As Variant
sAmpersand = Split(p, " & ")
sProd = Split(sAmpersand(0), ", ")
sProd(UBound(sProd)) = sAmpersand(1)
Dim ProductCount As Integer
Dim ProductEnd As Integer
ProductEnd = UBound(sProd) - 1
For ProductCount = 0 To ProductEnd
sProd(ProductCount) = Split(sProd(ProductCount), " ")
ProductCount = ProductCount + 1
Next ProductCount
Dim WordCount As Integer
Dim WordEnd As Integer
WordEnd = UBound(sProd(ProductCount)) - 1
Abbrev = StrConv(sProd(0)(0), vbProperCase)
For ProductCount = 0 To ProductEnd
For WordCount = 0 To WordEnd
If ProductCount = 0 Then
WordCount = 1
End If
Abbrev = Abbrev & Left(sProd(ProductCount)(WordCount), 1)
WordCount = WordCount + 1
Next WordCount
If ProductCount + 1 < ProductEnd Then
Abbrev = Abbrev & "_"
End If
ProductCount = ProductCount + 1
Next ProductCount
End Function
Working code:
Function Abbrev(p As String) As String
Dim res As String, w1, w2
res = Split(Split(p, ",")(0), " ")(0)
If res = Split(p, ",")(0) Then res = res & "_"
For Each w1 In Split(Mid(Replace(p, " &", ","), Len(res) + 1), ",")
For Each w2 In Split(w1, " ")
res = res & Left(w2, 1)
Next w2
res = res & "_"
Next w1
Abbrev = IIf(Right(res, 1) <> "_", res, Left(res, Len(res) - 1))
End Function
Here's a better abbreviate function:
Function Abbreviate(Name As String) As String
Dim I As Integer
Dim sResult As String
Dim sTemp As String
I = InStr(Name, " ")
If I < 1 Then
Abbreviate = Name
Exit Function
End If
sResult = Left$(Name, I)
sTemp = Name
Do While I > 0
sTemp = Right$(sTemp, Len(sTemp) - I)
If Left$(sTemp, 1) = "(" Then
If Mid$(sTemp & "***", 3, 1) = ")" Then
sResult = sResult & " " & Left$(sTemp, 3)
Else
sResult = sResult & " " & Left$(sTemp, 1)
End If
Else
sResult = sResult & " " & Left(sTemp, 1)
End If
I = InStr(sTemp, " ")
Loop
Abbreviate = sResult
End Function
This is from user al_b_cnu on mrexcel.com
Here is a modified version to shorten up the result a bit:
Function Abbreviate(Name As String) As String
Dim I As Integer
Dim sResult As String
Dim sTemp As String
I = InStr(Name, " ")
If I < 1 Then
Abbreviate = Name
Exit Function
End If
sResult = Left$(Name, I)
sTemp = Name
Do While I > 0
sTemp = Right$(sTemp, Len(sTemp) - I)
If Left$(sTemp, 1) = "(" Then
If Mid$(sTemp & "***", 3, 1) = ")" Then
sResult = sResult & Left$(sTemp, 3)
Else
sResult = sResult & Left$(sTemp, 1)
End If
Else
sResult = sResult & Left(sTemp, 1)
End If
I = InStr(sTemp, " ")
Loop
Abbreviate = sResult
End Function