I have a word document. It contains timestamps which I need to modify.
I'm using VBA to modify the timestamps. I been able to find the timestamps. I been able to extract a timestamp and adjust the extracted time in the timestamp. I have not been able to replace the old timestamp.
Question: What VBA do I need to replace the old timestamp?
shouldn't be hard, but I don't know the vba nor word lingo to do a google search.
I'm working with a Word document. I'll provide some plain text so to avoid issues with a raw word document. example text: https://pastebin.com/raw/nf4Cc8bu
Here is the code I have.
Sub FindAndReplace()
'
' vba string functions
' https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/functions/string-functions
' https://www.eng.auburn.edu/~tplacek/courses/3600/Strings%20and%20Manipulations.htm
'
Dim c As Range
Dim StartWord As String, EndWord As String
Debug.Print
Debug.Print "start of FindAndReplace() at " & Time() & " on " & Date
Debug.Print "ActiveWindow.Parent (word document name) is " & ActiveWindow.Parent
Debug.Print
Set c = ActiveDocument.Content
c.Find.ClearFormatting
c.Find.Replacement.ClearFormatting
With c.Find
.Text = "[0-9][0-9]:[0-9][0-9]:[0-9][0-9]" ' Time stamp format
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = True
.MatchSoundsLike = False
.MatchAllWordForms = False '
End With
Dim FirstDate As Date ' Declare variables.
Dim IntervalType As String
Dim Number As Integer
Dim message As String
' For how much time do we need to adjust the timestamp so to match the video?
'Number = InputBox("Enter number of seconds")
Number = 45
Debug.Print "Number is " & Number
Debug.Print
IntervalType = "s" ' interval in seconds
c.Find.Execute
While c.Find.Found
Debug.Print "c.Text is " & c.Text
message = DateAdd(IntervalType, Number, c.Text)
Debug.Print "adjusted time stamp is " & Format(message, "hh:mm:ss")
'--> need to replace existing timestamp here.
Debug.Print
' get next timestamp
c.Find.Execute
Wend
Debug.Print "Good bye..."
End Sub
Related
Any help would be awesome. I have a macro that finds acronyms and applies a spell out of the acronym with the acronym in parenthesis. It is applying the spell out and acronym once but randomly. I need the macro to identify the first instance and apply the spell out only to that first instance. So if the first instance should look like this:
Be Right Back (BRB) some text BRB some text BRB
Right know it looks like this: BRB some text Be Right Back (BRB) some text BRB
The macro has the code " .Execute Replace:=wdReplaceOne" but it doesn't seem to be working.
Here's the code I am using:
Sub AcronymManager()
Application.ScreenUpdating = False
Dim FRDoc As Document, FRList As String, j As Long, StrExp As String, StrAcc As String
'Load the strings from the reference doc into a text string to be used as an array.
Set FRDoc = ThisDocument
'Alternative code to use a different document the reference doc:
'Set FRDoc = Documents.Open("C:\Users" & Environ("UserName") & "\Documents\AcronymList.doc")
If ActiveDocument = FRDoc Then
MsgBox "Error: Cannot process this document - it's the source document", vbCritical
Exit Sub
End If
FRList = FRDoc.Range.Text
If FRDoc <> ThisDocument Then FRDoc.Close wdDoNotSaveChanges
Set FRDoc = Nothing
With ActiveDocument.Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = True
.MatchWholeWord = True
.MatchCase = True
.Wrap = wdFindContinue
'Process each word from the Check List. Tab-delimited strings are assumed, formatted as:
'Find text <Tab> Replace text
For j = 0 To UBound(Split(FRList, vbCr)) - 1
StrExp = Split(Split(FRList, vbCr)(j), vbTab)(0)
StrAcc = Split(Split(FRList, vbCr)(j), vbTab)(1)
.Text = StrExp
.Replacement.Text = StrAcc
.Execute Replace:=wdReplaceAll
.Text = "(" & StrAcc & ")"
.Execute Replace:=wdReplaceAll
.Text = StrAcc & "^w" & StrAcc
.Execute Replace:=wdReplaceAll
.Text = StrAcc
.Replacement.Text = StrExp & " (" & StrAcc & ")"
.Execute Replace:=wdReplaceOne
Next
End With
Application.ScreenUpdating = True
End Sub
I am trying to tweak/add to a type case macro I made and have been working on that I use in MS-Word (mac). I am trying to add to the macro to recognize specific abbreviations and convert them to a specific type case. For example, converting "ml" or "Ml" or "ML" to mL. Converting "gm" or "Gm" or "GM" to g.
I have attached my code below of what I have so far that fixes/ignores capitalizations, I just need help adding in these new rules. I am guessing I would have to create a bunch of specific If/Then statements, but I am not exactly sure.
Sub CaseFix()
'
' CaseFix Macro
'
'
Dim lclist As String
Dim wrd As Integer
Dim sTest As String
' list of lowercase words, surrounded by spaces
lclist = " of or the by your to this into at but with on compare compared is in for from a an and cm min minutes minute sec seconds mL gm g "
Selection.Range.Case = wdTitleWord
For wrd = 2 To Selection.Range.Words.Count
sTest = Trim(Selection.Range.Words(wrd))
sTest = " " & LCase(sTest) & " "
If InStr(lclist, sTest) Then
Selection.Range.Words(wrd).Case = wdLowerCase
End If
Next wrd
End Sub
For an existing document:
Sub CaseFix()
Application.ScreenUpdating = False
Dim FList As String, RList As String, j As Long
FList = "aaa,aba,aca,ada"
RList = "AAa,aBa,ACA,AdA"
With ActiveDocument.Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Format = False
.Forward = True
.MatchWholeWord = True
.MatchWildcards = False
'Process each word from the Find/Replace Lists
For j = 0 To UBound(Split(FList, ","))
.Text = UCase(Split(FList, ",")(j))
.Replacement.Text = Split(RList, ",")(j)
.MatchCase = False
.Execute Replace:=wdReplaceAll
.MatchCase = True
.Execute Replace:=wdReplaceAll
Next
End With
Application.ScreenUpdating = True
End Sub
Note that you must have the same number of comma-separated entries in the FList and RList.
I have a macro which searches for a paragraph break ("^p") in a selection of text. I notice that, in the Advanced Find & Replace Screen, word tells you how many instances of the search item has been found. How do I extract this count?
I have recorded a VBA macro which does the find in a selection, but I don't know how to extract the number of occurrences from that selection. Does anyone know how to do this (would prefer to just extract it from the find&replace function as opposed to writing a for-loop)?
Selection.Find.ClearFormatting
With Selection.Find
.Text = "^p"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
You can't - that isn't exposed to the developer, unfortunately!
But you don't necessarily have to loop Word's Find. You can use other functionality which executes faster than the object model to count the number of instances of a string. For example loop Instr to count the number of instances:
Sub TestGetCountOfFoundInstances()
Dim rng As Word.Range
Dim searchTerm As String
Dim nrInstances As Long
Dim bFound As Boolean
searchTerm = Chr(13)
Set rng = Selection.Range
nrInstances = CountNrInstancesSearchTerm(rng, searchTerm)
Debug.Print "The term " & searchTerm & " was found " & nrInstances & _
" times."
bFound = rng.Find.Execute(findText:="^p", ReplaceWith:="^l", Replace:=wdReplaceAll)
End Sub
Function CountNrInstancesSearchTerm( _
rng As Word.Range, searchTerm As String) As Long
Dim counter As Long, loc As Long, startPos As Long
Dim t As String
t = rng.Text
startPos = 1
Do
loc = InStr(startPos, t, searchTerm)
If loc > 0 Then
counter = counter + 1
startPos = loc + 1
End If
Loop While loc > 0
CountNrInstancesSearchTerm = counter
End Function
I am working with Word Docs containing quite a lot of pages and formulas.
I have an array containing expressions
dim YellowWord(1 to 100) as string
I want to start at the beginning of the word text to look for every of those words and have a look the instances where that word or expression is followed by a number or numbers into brackets
EXMAPLE:
yellowword(2)="the blue table"
using wildcards I can find: the blue table (34, 23) in the text.
what I want is filling another array that would be:
yellowwood_reference(2) = "(34, 23)"
the code I have is so:
for i=1 to NRofYellowWords
with active document.content.find
.clearformating
.text = yellowWord(i) & " " & "\((*)\)"
with .replacement
.clearformating
.text = yellowWord(i) & "(\1)"
'HERE IS WHERE I WANT TO SAY TO WORD:
'PUT THAT PART "(\1)" INTO A VARIABLE YELLOWWORD_REFERENCE(i)
'HOWW??????
.font.color = wdcolorred
'here i changed the color of the string with the references into red.
end with
.fordward = true
.wrap = wdfindcontinue
.format = true
.matchcase = false
.matchewholeword = false
.matchwildcards = true
.matchsoundslike = false
.matchallwordforms= false
.execute replace:=wdreplaceall
end with
next i
In the above code there are several problems:
the first one I wrote it in capital letters, getting that reference of the wild card into a variable.
The second one is that there might be many appearances of the YellowWord(2) in the text, I only need/want the first reference, not the rest. That means that the first time the code finds the blue table (24,26) after passing the value "(24, 26)" into another array the code should move on and not look for more instances of the blue table in the text.
btw, i used wildcards because there might be the case that the references are simple not into brackets, so i would have to run everything twice with a different wildcard.
By the way as you can imagine, once I get the array yellowWord_reference(i) I would add the references there where there are instances of YellowWord without refferences.
I would really appreciate help since I really clicked many websites with little success.
thanks a lot
cheers
PS: If you think that there is a better way to do all that without using .find just mention it please, i am quite new in Ms-Word and coming from VBA Excel i get headaches figuring out where is the selection point.
I modified your code so that if it finds your 'words', it will capture the numbers that follow.
The code you posted would never work due to the number of compile errors ... strongly suggest you start using "Option Explicit" and posting actual code rather than typing in in yourself.
Other notes:
The numbers are enclosed in parenthesis () - not brackets []
You were using a 'ReplaceAll'; if you only wanted the first occurance, change from '...All'
I removed the 'red font' and 'Replace' ... add it back if needed.
Your code would remove the space between the word and the number - is that what you wanted?
Here's the code:
Option Explicit
Sub Find_Words()
Dim yellowWord(100) As String
Dim yellowwood_reference(100) As String
Dim NRofYellowWords As Integer
Dim i As Integer
Dim lS As Long
Dim lE As Long
Dim sFound As String
Dim rng As Range
yellowWord(1) = "blue table"
yellowWord(2) = "little"
yellowWord(3) = "big"
yellowWord(4) = "xxx last xxx"
NRofYellowWords = 4
Set rng = ActiveDocument.Range
For i = 1 To NRofYellowWords
With rng.Find
.Text = yellowWord(i) & " " & "\((*)\)"
With .Replacement
.Text = yellowWord(i) & "(\1)"
End With
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = True
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
If .Found Then
' Find (numbers) & save
lS = InStr(rng.Start, ActiveDocument.Range.Text, "(")
If lS > 0 Then
lE = InStr(lS, ActiveDocument.Range.Text, ")")
sFound = Mid(ActiveDocument.Range.Text, lS, lE - lS + 1)
yellowwood_reference(i) = sFound
Debug.Print "Found: " & yellowWord(i) & vbTab & sFound
Else
MsgBox "Bad format; missing '('" & vbTab & Mid(ActiveDocument.Range.Text, lS, 50)
End If
Else
Debug.Print "Not Found: " & yellowWord(i)
End If
End With
Next i
Debug.Print "Finished"
End Sub
I am in the process of putting together a Word macro (below) that parses a table of acronyms in one Word document and highlights every occurrence of these acronyms in another Word document. This appears to be functional.
However, I would like to also have the macro differentiate acronyms that are in parentheses from those that are not. For example,
The soldier is considered Away Without Leave (AWOL). AWOL personnel are subject to arrest.
It seems as though the range "oRange" that defines the found acronym could be evaluated, if it is first expanded in the Do-While loop using this code:
oRange.SetRange Start:=oRange.Start - 1, End:=oRange.End + 1
However, none of my attempts to code a solution seem to work (they put the macro into an infinite loop or result in error messages). I'm fairly new to VBA programming and am obviously missing something regarding how the loops are operating.
My question is: is there a way to duplicate the range "oRange" for subsequent manipulation or is there some other method that I should be using?
Thanks for any assistance you can provide!
Sub HighlightAcronyms()
Dim wdDoc As Object
Dim wdFileName As Variant
Dim TableNo As Integer 'table number in Word
Dim oRow As Row
Dim oCell As Cell
Dim sCellText As String
Dim oDoc_Source As Document
Dim strListSep As String
Dim oRange As Range
Dim n As Long
Dim sCellExpanded As String
'Application.ScreenUpdating = False
strListSep = Application.International(wdListSeparator)
'*** Select acronym file and check that it contains one table
wdFileName = WordApplicationGetOpenFileName("*.docx", True, True)
If wdFileName = False Then Exit Sub '(user cancelled import file browser)
Set wdDoc = GetObject(wdFileName) 'open Word file
With wdDoc
TableNo = wdDoc.Tables.Count
If TableNo = 0 Then
MsgBox "The file """ & wdFileName & """ contains no tables.", _
vbExclamation, "Import Word Table"
ElseIf TableNo > 1 Then
MsgBox "The file """ & wdFileName & """ contains multiple tables.", _
vbExclamation, "Import Word Table"
End If
End With
'*** steps through acronym column
wdDoc.Tables(1).Cell(1, 1).Select
Selection.SelectColumn
For Each oCell In Selection.Cells
' Remove table cell markers from the text.
sCellText = Left$(oCell.Range, Len(oCell.Range) - 2)
sCellExpanded = "(" & sCellText & ")"
n = 1
'need to find foolproof method to select document for highlighting
Documents(2).Activate
Set oDoc_Source = ActiveDocument
With oDoc_Source
Set oRange = .Range
With oRange.Find
.Text = sCellText
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = True
.MatchWildcards = False
Do While .Execute
If n = 1 Then
oRange.HighlightColorIndex = wdGreen
Else
oRange.HighlightColorIndex = wdYellow
End If
'trying to add code here to expand oRange and compare it to sCellExpanded
n = n + 1
Loop
End With
End With
Next oCell
Set wdDoc = Nothing
End Sub
Try This
Define two ranges instead of merging the oRange.
See this sample code (TRIED AND TESTED)
Sub Sample()
Dim strSearch As String, sCellExpanded As String
Dim oRange As Range, newRange As Range
strSearch = "AWOL"
sCellExpanded = "(" & strSearch & ")"
Set oRange = ActiveDocument.Range
With oRange.Find
.ClearFormatting
.Text = strSearch
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While .Execute
If n = 1 Then
oRange.HighlightColorIndex = wdGreen
Else
oRange.HighlightColorIndex = wdYellow
End If
'~~> To check if the found word is not the 1st word.
If oRange.Start <> 0 Then
Set newRange = ActiveDocument.Range(Start:=oRange.Start - 1, End:=oRange.End + 1)
If newRange.Text = sCellExpanded Then
'
'~~> Your code here
'
newRange.Underline = wdUnderlineDouble
End If
End If
n = n + 1
Loop
End With
End Sub
SNAPSHOT
Unable to upload image at the moment. imgur server is down at the moment.
You may see this link
http://wikisend.com/download/141816/untitled.png