PDA

View Full Version : Insert part of filename in word



vik1
11-06-2017, 03:14 AM
I wish to insert part of my filename in body of my document at one place.


The filenames can be,


36-gamon_rx-ric_la-630212--dd09162017-


or


36-stephen_ru-sam_greg-731234-286530-dd10172017-p


etc.


The pattern being, any english alphabet, followed by a hyphen, followed by any arabic number,


for eg, as above,
"a-9"
or
"g-7"
, wherein the arabic number followed by the letter is always 6 digits, but the number keeps


changing.




The numbers and alphabets will keep on changing, but the above pattern ( eg, "a-9" ) will


always remain.


I wish to truncate the filename, so only the 6-digit number is populated in the body of the


word document.




I have created a macro, using word > insert > quickparts, filename, but it inserts the entire filename. I am not able to truncate the filename to insert only the 6-digit number.

Any help would be greatly appreciated.

Thank you.

gmayor
11-06-2017, 04:58 AM
You can split the name by the hyphens then evaluate the segments and then get the segment you wish e.g. the following will type the first six digit number at the cursor, if it exists


Option Explicit

Sub GetNumberFromName()
'Graham Mayor - http://www.gmayor.com - Last updated - 06 Nov 2017
Dim strNum As String
Dim vName As Variant
Dim iNum As Integer
Dim bFound As Boolean
If InStr(1, ActiveDocument.Name, "-") > 0 Then
vName = Split(ActiveDocument.Name, "-")
For iNum = LBound(vName) To UBound(vName)
strNum = Trim(vName(iNum))
If Len(strNum) = 6 And IsNumeric(strNum) = True Then
bFound = True
Exit For
End If
Next iNum
If Not bFound Then GoTo lbl_Exit
'do something with strnum e.g.
Selection.Range.Text = strNum
End If
lbl_Exit:
Exit Sub
End Sub

vik1
11-06-2017, 05:39 AM
Thanks a Million ! You are a Genius !

Can you suggest how to insert the result of this macro, at a particular location in the file, say replace (PartOfFileNumber) with strNum

vik1
11-06-2017, 05:43 AM
OK, Got !






Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.text = "PartOfFileNumber"
.Replacement.text = strNum
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
With Selection
If .Find.Forward = True Then
.Collapse direction:=wdCollapseStart
Else
.Collapse direction:=wdCollapseEnd
End If
.Find.Execute Replace:=wdReplaceOne
End With