Okay, I've searched and searched and am hoping someone here can help me out.
I've been trying to get a VBScript program to open a word document, search for a specific char and replace it with a Addin field (i.e. { SEQ # } )
Here's what I have thus far:
1 Const wdReplaceAll = 2
2 Set objWord = CreateObject("Word.Application")
3 objWord.Visible = True
4
5 Set ObjDoc = objWord.Documents.Open("C:\path\to\.doc")
6 Set objSelection = objWord.Selection
7
8 objSelection.Find.Text = "#"
9 objSelection.Find.Forward = True
10 objSelection.MatchWholeWord = True
11
12 objSelection.Find.Replace.Text = "replacement text"
13
14 objSelection.Find.Execute ,,,,,,,,,,wdReplaceAll
This code works for "Find/Replace" but does not work for fields.
Much help would be awesome! Thanks!
Replace replaces text, but you want to add a field. That's an entirely different thing. I'd suggest to Find the search text (leaves the text selected) and then Add the field (replaces the selected text):
With objWord.Selection
.Find.Text = "#"
.Find.Forward = True
.Find.MatchWholeWord = True
.Find.Execute
.Fields.Add .Range, -1, "SEQ #", True
End With
To replace all occurrences of the search string you have to create a loop that keeps executing .Find.Execute until no further occurrences are found. The return value of the Execute method indicates if another match was found.
With objWord.Selection
.Find.Text = "#"
.Find.Forward = True
.Find.MatchWholeWord = True
Do
found = .Find.Execute
If found Then .Fields.Add .Range, -1, "SEQ #", True
Loop While found
End With
Make sure your cursor is positioned at the beginning of the document before you run the above code, otherwise you might miss occurrences of your search text.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
I am having an issue with the MID() function in VBScript
Here are some sample lines I do have in my text.
::UNm DL=254 DH=409.3 DS=16.2
::UNm DL=254.3 DH=409.3 DS=16.2
::UNm DL=254.32 DH=409.3 DS=16.2
::UNm DL=254.325 DH=409.3 DS=16.2
I am reading a txt file, and I wish to extract the value contained in between DL= and DH=
Now the value as you can see will vary.
dataline = InFile.ReadLine
Mid(Dataline, Instr(Dataline,"DL")+3, Len(Dataline) - (InstrRev(Dataline,"DH=")-Instr(Dataline,"DL")+3))
and also tried
Mid(Dataline, Instr(Dataline,"DL")+3, Len(Dataline) - (InstrRev(Dataline,"DH=")-Instr(Dataline,"DL")-3))
Seems the results vary from one time to the other. What am I doing wrong?
There can be multiple ways to fetch the desired value:
Using Mid method
Dim line : line = "::UNm DL=254.325 DH=409.3 DS=16.2"
MsgBox getValueByMid(line)
Function getValueByMid(strLine)
Dim sDelim, sPos, eDelim, ePos
sDelim = "DL="
eDelim = "DH="
sPos = InStr(1,strLine,sDelim,1)
ePos = InStr(1,strLine,eDelim,1)
getValueByMid = Mid(strLine,sPos+Len(sDelim),ePos-(sPos+Len(sDelim)))
End Function
Using Regular Expression
Dim line : line = "::UNm DL=254.325 DH=409.3 DS=16.2"
MsgBox getValueByRegex(line)
Function getValueByRegex(strLine)
Dim regex, matches
Set regex = New RegExp
regex.Global = True
regex.Multiline = True
regex.Pattern = "\bDL=(.+?)DH=" 'captures all the contents between DL= and DH= and stores it in Group 1
Set matches = regex.Execute(strLine)
If matches.count > 0 Then
getValueByRegex = matches(0).submatches(0) 'matches(0) - means first match; submatches(0) - 1st group of the current match
Else
getValueByRegex = ""
End If
End Function
Regex Demo
Explanation:
\b - matches a word-boundary
DL= - matches DL=
(.+?) - matches 1 or more occurences of any character, as few as possible and captures this submatch in Group 1 of the match
DH= - matches DH=.
Using split method
Dim line : line = "::UNm DL=254.325 DH=409.3 DS=16.2"
MsgBox getValue(line)
Function getValue(strLine)
getValue = Split(Split(strLine,"DL=")(1),"DH=")(0)
End Function
Output:
I am trying to search through Word documents and try to find a certain character. The ± character to be precise. The code can find the character because I have it print to screen if it found it. But it is unable to replace the character.
I have even tried searching for a random string I knew was in the files such as "3" and replacing it with something random such as "dog". But nothing works. It still finds the characters but does not replace.
Option Explicit
Dim objWord, objDoc, objSelection, oFSO, folder, jj, file
Set objWord = CreateObject("Word.Application")
objWord.Visible = False: objWord.DisplayAlerts = False
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set folder = oFSO.GetFolder("C:\Users\Desktop\myFolder")
For Each file In folder.Files
objWord.Documents.Open file.path, False, True ' path, confirmconversions, readonly
Set objDoc = objWord.ActiveDocument
Set objSelection = objWord.Selection
objSelection.Find.Forward = True
objSelection.Find.MatchWholeWord = False
objSelection.Find.Text = ChrW(177)
objSelection.Find.Replacement.Text = "ChrW(177)"
objSelection.Find.Execute
If objSelection.Find.Found = True then
Wscript.echo "Character Found"
End If
objDoc.close
Next
objWord.Quit
The problem is that the code in the question doesn't specify that a replacement should take place. This is set in the Execute method, as a parameter.
Since this is VBScript rather than VBA it's not possible to use the enumerations (such as wdReplaceAll). Instead, it's necessary to specify the numeric equivalent of an enumeration. VBA without enumerations...
objSelection.Find.Execute Replace:=2, Forward:=True, Wrap:=0
However, VBScript doesn't accept named arguments, so all the arguments need to be specified by position, with "empty commas" if nothing should be specified.
objSelection.Find.Execute , , , , , , , 0, , , 2
To discover the numeric equivalent consult either the VBA Object Library (F2 in the VBA Editor), the Language Reference or use the Immediate Window (Ctrl+G) in the VBA Editor like this: ?wdReplaceAll then press Enter.
objSelection.Find.Execute
should be
objSelection.Find.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
(assuming you want to replace all occurrences
This code running inside a word module will replace all "cat" with "dog"
Sub test()
Dim objdoc As Document
Dim objSelection As Range
Set objdoc = ActiveDocument
Set objSelection = Selection.Range
With objSelection.Find
.Forward = True
.MatchWholeWord = False
.Text = "Cat"
.Replacement.Text = "Dog"
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
If .Found Then
Debug.Print "Found"
End If
End With
End Sub
However you're running in vbscript using late binding, so possibly there's a type issue - you're selection object may not be a range but a variant?
I need to create an excel sheet which contains a visual representation of a bit array. Presently I test the bit value and update the cell contents
For h = 1 To 128
value = Mid(array, h,1)
If value = "1" Then
xl.Application.Sheets("Sheet1").Cells(129 - h,5).value = "X"
Else
xl.Application.Sheets("Sheet1").Cells(129 - h,5).value = ""
End If
Next
If I add a WScript.Sleep 100 before Next then the output result in the excel sheet is correct.
If not, then the X's are in the wrong places.
Initially I thought that it was Excel that was slow, so I tried making a CSV file that I could simply import later, but with the same results: too fast and the X's are in the wrong positions, slow it down and they are correct.
There are around 128 of these 128bit arrays, and if each takes 3 ~ 5 seconds then making this sheet will take forever.
Does anyone know how I can achieve this quickly? I am open to other ideas/solutions (with VBS) outputting the excel file.
Thanks!
Try putting the array into the range in one go, like this
ReDim dat(1 To 128, 1 To 1)
For h = 1 To 128
v = Mid$(arr, h, 1)
dat(129 - h, 1) = IIf(v = "1", "X", "")
Next
xl.Application.Sheets("Sheet1").Cells(1, 5).Resize(128, 1).Value = dat
This worked for me (tested in vbscript rather than vba).
As it uses an array, the "" output as part of an IF is redundant as the array is blank, so it is only necessary to write the X when the bit is 1.
Dim StrArr
Dim xl
Set xl = CreateObject("excel.application")
Set wb = xl.Workbooks.Add
'sample array
StrArr = "1100111011001110110011101100111011001110110011101100111011001110110011101100111011001110110011101100111011001110110011101100111"
Dim X(128, 1 )
For lngrow = 1 To UBound(X)
If Mid(StrArr, lngrow, 1) = "1" Then X(lngrow, 0) = 1
Next
wb.Sheets(1).Cells(1, 5).Resize(UBound(X), 1).Value = X
xl.Visible = True
Here I have a small VBS script that helps me append a new line to a table in MS "Word" 2003:
Set wd = CreateObject("Word.Application")
wd.Visible = True
Set doc = wd.Documents.Open ("c:\addtotable.doc")
Set r = doc.Tables(1).Rows.Add
aa = Split("turtle,dog,rooster,maple", ",")
For i = 0 To r.Cells.Count - 1
r.Cells(i + 1).Range.Text = aa(i)
Next
It works fine, but it doesn't save anything. I want it to save the performed changes.
By the method of macro-recording in the "Word" I got this macro command that saves active "Word" document:
ActiveDocument.Save
So, I decided to append this macro to the VBS script above:
Set wd = CreateObject("Word.Application")
wd.Visible = True
Set doc = wd.Documents.Open ("c:\addtotable.doc")
Set r = doc.Tables(1).Rows.Add
aa = Split("turtle,dog,rooster,maple", ",")
For i = 0 To r.Cells.Count - 1
r.Cells(i + 1).Range.Text = aa(i)
Next
ActiveDocument.Save
But it doesn't save anything. What am I doing wrong here?
Have you already tried calling doc.Save after making those changes? If that doesn't work:
The issue is that ActiveDocument doesn't automatically reference what you think it does in VBScript the way it does in Word's VBA.
Try setting a new variable to the active document, like so:
Dim activeDoc
Set activeDoc = wd.ActiveDocument
activeDoc.Save
I think you have to use ActiveDocument.SaveAs("C:\addtotable.doc"); because I can't find any documentation for .Save. SaveAs accepts a second parameter which specifies what format to save it in. Pastebin of the parameters here.
I'm gettinga n error message in line 8 when I try to call out the script to stop when it finds teh attribute in the Web page: field in AD.
Set objSysInfo = CreateObject("ADSystemInfo")
strUserDN = objSysInfo.UserName
Set objUser = GetObject("LDAP://" & strUserDN)
strwWWHomePage = objItem.Get("wWWHomePage")
If wWWHomePage 6 Then
wscript.quit
Else
Set ppt = CreateObject("PowerPoint.Application")
ppt.Visible = True
ppt.Presentations.Open "\\abngan01\tracking\ppt.pptx"
End If
You have:
If wWWHomePage 6 Then
I'm assuming you want it to say:
If wWWHomePage = 6 Then
Since the missing "=" will cause an error, but since that code really doesn't do anything anyway, other than just abort the script, you could simplify your code by only taking action if that value is not set, for example:
If objItem.Get("wWWHomePage") <> 6 Then
Set ppt = CreateObject("PowerPoint.Application")
ppt.Visible = True
ppt.Presentations.Open "\\abngan01\tracking\ppt.pptx"
End If
I'm also assuming "6" is some sort of flag you've set yourself, you might want to use something a little more descriptive like "PPTSTATUS006", or something along those lines.