VB6 Word find and replace in header Late Bound - replace
I found this code for find and replace everywhere with VB6 in Word files, however it is early bound.
However I need it for late bound, since my EXE will be used on different systems, thus I can't use the Reference to Word Library.
What my code needs to do is:
Find Red text in all Word files and replace it with hidden font.
I had it working for the main text, but the header also contains red text and also needs to be hidden.
Here is my current code, which does not replace anything anymore.
Private Sub PREP_Click()
Const wdColorRed = 255
Dim oWordApp As Object
On Error Resume Next
Dim fs As Object
Dim rngStory As Object
Dim lngJunk As Long
Dim oFolder As Object
Dim tFolder As Object
Dim oFile As Object
Dim strDocName As String
Dim strPathName As String
Dim locFolder As String
locFolder = InputBox("Enter the folder path to the file(s) your want to prepare.", "File Preparation", "Type your path here... Make sure it end with a back slash, e.g. C:\myfiles\")
Set fs = CreateObject("Scripting.FileSystemObject")
Set oFolder = fs.GetFolder(locFolder)
Set tFolder = fs.CreateFolder(locFolder & "PREP")
Set tFolder = fs.GetFolder(locFolder & "PREP")
Set oWordApp = CreateObject("Word.Application")
Set rngStory = CreateObject("Word.Range")
For Each oFile In oFolder.Files
oWordApp.Visible = False
oWordApp.Documents.Open (oFile.Path)
lngJunk = oWordApp.ActiveDocument.Sections(1).Headers(1).range.StoryType
'Iterate through all story types in the current document
For Each rngStory In oWordApp.ActiveDocument.StoryRanges
'Iterate through all linked stories
Do
With oWordApp.rngStory.Find
oWordApp.rngStory.WholeStory
oWordApp.rngStory.Find.Font.Hidden = True
oWordApp.rngStory.Find.Replacement.Font.Hidden = False
oWordApp.rngStory.Find.Execute Replace:=2
End With
'Get next linked story (if any)
Set rngStory = rngStory.NextStoryRange
Loop Until rngStory Is Nothing
Next
strDocName = oWordApp.ActiveDocument.Name
oWordApp.ChangeFileOpenDirectory (tFolder)
oWordApp.ActiveDocument.SaveAs FileName:=strDocName
oWordApp.ChangeFileOpenDirectory (oFolder)
Next oFile
oWordApp.Quit
Set rngStory = Nothing
Set oWordApp = Nothing
End Sub
I think the problem is the rngStory part. Please help!
That code is not early bound Ben. It's late bound.
Dim oWordApp As Object
Set oWordApp = CreateObject("Word.Application")
Is late bound, every where your dealing with Object your dealing with a late binding.
I used Selection instead of Range and it is working now:
Private Sub PREP_Click()
Const wdColorRed = 255
Dim oWordApp As Object
On Error Resume Next
Dim fs As Object
Dim rngStory As Object
Dim myDoc As Object
Dim oFolder As Object
Dim tFolder As Object
Dim oFile As Object
Dim strDocName As String
Dim strPathName As String
Dim locFolder As String
locFolder = InputBox("Enter the folder path to the file(s) your want to prepare.", "File Preparation", "Type your path here... Make sure it end with a back slash, e.g. C:\myfiles\")
Set fs = CreateObject("Scripting.FileSystemObject")
Set oFolder = fs.GetFolder(locFolder)
Set tFolder = fs.CreateFolder(locFolder & "PREP")
Set tFolder = fs.GetFolder(locFolder & "PREP")
Set oWordApp = CreateObject("Word.Application")
For Each oFile In oFolder.Files
oWordApp.Visible = False
oWordApp.Documents.Open (oFile.Path)
oWordApp.ActiveDocument.Sections(1).Headers(1).Range.Select
oWordApp.Selection.WholeStory
oWordApp.Selection.Find.Font.Color = wdColorRed
oWordApp.Selection.Find.Replacement.Font.Hidden = True
oWordApp.Selection.Find.Execute Replace:=2
oWordApp.ActiveDocument.Select
oWordApp.Selection.WholeStory
oWordApp.Selection.Find.Font.Color = wdColorRed
oWordApp.Selection.Find.Replacement.Font.Hidden = True
oWordApp.Selection.Find.Execute Replace:=2
strDocName = oWordApp.ActiveDocument.Name
oWordApp.ChangeFileOpenDirectory (tFolder)
oWordApp.ActiveDocument.SaveAs FileName:=strDocName
oWordApp.ChangeFileOpenDirectory (oFolder)
Next oFile
oWordApp.Quit
Set oWordApp = Nothing
End Sub
Related
Run script only if file does not exist
In my VBScript I am trying to run another VBScript to create a desktop shortcut if that desktop shortcut doesn't exist. If the desktop link does exist, it should not do anything. However, currently even if the desktop shortcut exists, the VBScript still runs. Why? No syntax error. Dim objFSO, strDirectory, strFile Set oShell = CreateObject ("WScript.Shell") 'getting script location strPath = WScript.ScriptFullName Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.GetFile(strPath) strFolder = objFSO.GetParentFolderName(objFile) 'define directory & file strDirectory = oShell.ExpandEnvironmentStrings("%USERPROFILE%") strFile = strDirectory & "\Desktop\My Program.lnk" If objFSO.FileExists(strFile) Then 'DO NOTHING Else strDesk = "desktoplink.vbs" oShell.Run strDesk, 0, False End If 'enclosing path to support spaces HMIpath = strFolder & "\CHK.bat" HMIpath = """" & HMIpath & """" Dim strArgs strArgs = "cmd /c " & HMIpath oShell.Run strArgs, 0, False
Getting the current url from the webbrowser
I've been trying to figure out how to get the current url to be used by the webbrowser in the following code: Dim t As String = client.DownloadString("browserurl") Here is my code so far: Dim client As New WebClient Dim t As String = client.DownloadString("browserurl") Dim p As String = "" Dim r As New System.Text.RegularExpressions.Regex(p) Dim v As String = reg.Match(t).Value I'm trying to parse data from the websites which the webbrowser is visiting.
How to extract youtube video id with Regex.Match
i try to extract video ID from youtube using Regex.Match, for example I have www.youtube.com/watch?v=3lqexxxCoDo and i want to extract only 3lqexxxCoDo. Dim link_vids As Match = Regex.Match(url_comments.Text, "https://www.youtube.com/watch?v=(.*?)$") url_v = link_vids.Value.ToString MessageBox.Show(url_v) how i can extract video id ?, thanks !
Finally got the solution Dim Str() As String Str = url_comments.Text.Split("=") url_v = Str(1)
Private Function getID(url as String) as String Try Dim myMatches As System.Text.RegularExpressions.Match 'Varible to hold the match Dim MyRegEx As New System.Text.RegularExpressions.Regex("youtu(?:\.be|be\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)", RegexOptions.IgnoreCase) 'This is where the magic happens/SHOULD work on all normal youtube links including youtu.be myMatches = MyRegEx.Match(url) If myMatches.Success = true then Return myMatches.Groups(1).Value Else Return "" 'Didn't match something went wrong End If Catch ex As Exception Return ex.ToString End Try End Function This function will return just the video ID.
you can basically replace "www.youtube.com/watch?v=" with "" using "String.Replace" MSDN String.Replace url.Replace("www.youtube.com/watch?v=","")
You can use this expression, in PHP I am using this. function parseYtId($vid) { if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $vid, $match)) { $vid = $match[1]; } return $vid; }
NUll reference exception at webrequest.create(URL)
I m getting a null reference exception in the line webrequest.create(v_strURL) Dim objHttpWebRequest As HttpWebRequest Dim objHttpWebResponse As HttpWebResponse Dim objRequestStream As Stream = Nothing Dim objResponseStream As Stream = Nothing Dim objXMLReader As XmlTextReader objHttpWebRequest = CType((WebRequest.Create(v_strURL)), HttpWebRequest) ''This line throws exception. The Url is correct and does give a proper response .
Simple Script With Logging
I am trying to write a script that will copy files from folder A to folder B, it will copy only files that come from a list file. I then need it to log any files that failed to copy. Here is what I have so far, I just cannot get logging to work. Option Explicit Dim Sour, Dest Dim oFSO, sFile, oFile, sText Dim objFSO, objFileCopy Dim strFilePath, strDestination, strSource Const ForReading = 1, ForWriting = 2, ForAppending = 8 strLoggingFiles = "C:\failedtransfer.txt" strSource = InputBox("Enter source path information") 'Enter your source path here strDestination = InputBox("Enter destination path information") 'Enter your destination path here 'Set the read of the input file and prompt for location Set oFSO = CreateObject("Scripting.FileSystemObject") sFile = InputBox("Enter path to text document with files to be copied:") 'Open the read, get the file name of the file to be copied, and copy it to new location If oFSO.FileExists(sFile) Then Set oFile = oFSO.OpenTextFile(sFile, ForReading) Do While Not oFile.AtEndOfStream sText = oFile.ReadLine If (Trim(sText) <> "") And _ oFSO.FileExists(strSource & "\" & sText) Then oFSO.CopyFile strSource & "\" & sText, strDestination Else WScript.Echo "Couldn't find " & strSource & "\" & sText End If Loop oFile.Close Else WScript.Echo "The file was not there." End If
Here's the code. It'll log the source file names (full path) if they are missing or failed when being copied. Please note that in Vista/Win7+, you'll need Administrator rights if you want to put a file in the root directory. Option Explicit Dim Sour, Dest Dim oFSO, oLog, sFile, oFile, sText Dim objFSO, objFileCopy Dim strFilePath, strDestination, strSource Const ForReading = 1, ForWriting = 2, ForAppending = 8 strLoggingFiles = "C:\failedtransfer.txt" strSource = InputBox("Enter source path information") 'Enter your source path here strDestination = InputBox("Enter destination path information") 'Enter your destination path here 'Set the read of the input file and prompt for location Set oFSO = CreateObject("Scripting.FileSystemObject") sFile = InputBox("Enter path to text document with files to be copied:") 'Open the read, get the file name of the file to be copied, and copy it to new location If oFSO.FileExists(sFile) Then 'Open/create log file set oLog = oFSO.OpenTextFile(strLoggingFiles, ForAppending, True) Set oFile = oFSO.OpenTextFile(sFile, ForReading) Do While Not oFile.AtEndOfStream sText = oFile.ReadLine If (Trim(sText) <> "") And _ oFSO.FileExists(strSource & "\" & sText) Then On Error Resume Next 'disable quit on error oFSO.CopyFile strSource & "\" & sText, strDestination If Err.Number <> 0 Then oLog.WriteLine strSource & "\" & sText 'log failed copy End If On Error Goto 0 'enable quit on error Else WScript.Echo "Couldn't find " & strSource & "\" & sText oLog.WriteLine strSource & "\" & sText 'log failed copy 'log missing source End If Loop oFile.Close oLog.Close 'close log file Else WScript.Echo "The file was not there." End If
At some point I got tired of writing logging routines over and over again, so I wrote a class (CLogger) as an abstraction layer for logging to different facilities (console, eventlog, file): Set clog = New CLogger clog.LogFile = "C:\failedtransfer.txt" clog.LogToConsole = False clog.LogToEventlog = False '... On Error Resume Next oFSO.CopyFile strSource & "\" & sText, strDestination If Err Then clog.LogError strSource & "\" & sText & ": " & FormatErrorMessage(Err) End If On Error Goto 0 '...