I want to be able read in two variables at a time into a VBScript. What I'm doing is replacing certain text from a bunch of HTML files. I have a script already written to do this, but I have to input only one set of text at a time. Command line Example:
C:> replace.vbs (OldText) (NewText)
where (OldText) and (NewText) are both parameters.
strOldText = WScript.Arguments.Item(0)
strNewText = WScript.Arguments.Item(1)
Is there a way to have a text file set up like:
(OldText) (NewText)
(OldText) (NewText)
(OldText) (NewText)
(OldText) (NewText)
and have the script read one at a time?
My find and replace code works perfectly. I would just like to automate the script to read the parameters from the text file rather than me typing them in one at a time in command prompt.
Any help is greatly appreciated. If further information is needed please let me know. I hope it's clear.
Thanks
Are you looking for something like this?
strDelimiter = " "
strInfilePath = "C:\Path to file to read.txt"
Const ForReading = 1
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objInfile = objFso.OpenTextFile(strInfilePath, ForReading)
Do While Not objInfile.AtEndOfStream
strLine = objInfile.ReadLine
arrParts = Split(strLine, strDelimiter)
strOldText = arrParts(0)
strNewText = arrParts(1)
Loop
I would probably use PowerShell for the whole thing instead of just to call the script, but I think this should work. If not, the problem is probably in how I'm trying to call the vbscript in my example.
PowerShell:
Import-CSV textReplace.csv | % {
wscript.exe replace.vbs $_.OldText $_.NewText
}
CSV content:
OldText,NewText
"String 1","String 2"
"String 3,"String 4"
Related
I am automating a web page extraction and writting the contents to a text (HTML) file.
For that I set up a File System Object like this
Dim myHTMLfilepath As String
myHTMLfilepath = "C:\temp\MyFile.html"
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim myHTMLFile As Object
Set myHTMLFile = fso.createtextfile(myHTMLfilepath)
When I try to write the extracted content to the file sometimes I get an error 5 (invalid parameter). Here is th code:
myHTMLFile.writeline objIE.document.getElementsByClassName("cool-box")(0).innerHTML
It breaks when the length of the innerHTML is somewhere between 25800 and 28000 (I haven't yet figured the exact limit).
Does anyone know if the WriteLine limit can be increased or advise on a different way to do this?
Assuming the .innerHTML can successfully be read into a string (split up reading/writing to find out), you should be able to use an ADODB.Stream to write it to the file. WriteLine is intended to write a single line of text to a file, not a whole entire document.
Dim contents As String
contents = objIE.document.getElementsByClassName("cool-box")(0).innerHTML
With CreateObject("ADODB.Stream")
.Open
.Type = 1
.Write contents
.SaveToFile myHTMLfilepath, 2
.Close
End With
I am using SSIS script task to replace text in text file. In my VB script hard coded file path in script but I want to use user variable instead.
Const ForReading = 1
Const ForWriting = 2
Dim objFSO, objFile, strText, strNewText
objFSO = CreateObject("Scripting.FileSystemObject")
objFile = objFSO.OpenTextFile("C:\Users\newtons\Desktop\Text.txt", ForReading)
strText = objFile.ReadAll
objFile.Close()
strNewText = Replace(strText, "Jim", "James")
objFile = objFSO.OpenTextFile("C:\Users\newtons\Desktop\Text.txt", ForWriting)
objFile.WriteLine(strNewText)
objFile.Close()
objFSO = Nothing
objFile = Nothing
Use #Alex's answer to add and reference variables. But just an FYI that you can do your entire script in 2 lines of code if you use System.IO.
so add this to the imports section
Import System.IO
Then use these lines in your MAIN Sub
Dim filePath As String = Dts.Variables("User::FullFilePath").Value.ToString()
File.WriteAllText(filePath, File.ReadAllText(filePath).Replace("Jim", "James"))
You can pass your customer variables to the [task script] in tab Script using ReadOnlyVariables and/or ReadWriteVariables, after having defined the variables globally; take a look here
More in detail:
to add variables to your project you can select the [Variables] tab in the upper left in the Package, than insert requirend fields:
Variables can be added to the [task script] by selecting them as ReadOnlyVariables and/or ReadWriteVariables:
so you can use within the [task script] by declaring:
Dts.Variables("User::Variable").Value
as #Matt says online documentation omits 'User::'
I have a code, in which I want to loop through files in a folder, check their built-in or custom document properties (without opening them), and later open those, which are meant to be open.
To do this, I'm using Shell and to set the folder I'm using Shell.Namespace.
The problem is with the Namespace, I guess. When I use a variable strSuborCesta for the path it doesn't work. When I print the variable strSuborCesta into immediate window and use the printed string inside the Shell.Namespace("....") it does work.
By it doesn't work I mean I get:
run-time error : 91 Object variable or With block not set
when I try to loop through the files in folder (which is not set in that case, so I understand why the error occurred, but don't understand why it's not accepting a string variable)
The path is correct in both ways. But I need it to be a variable, not a hardcoded string.
Where do I error?
Is there any better way, to check document properties (like comments, title, author, etc.) without opening the Excel files?
Below is the section (currently just in testing phase) that is giving me a hard time.
str[name of variable] variables are string data types. sFile, oShell, oDir are as Variants
'--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'get a root path
strPriecinokCesta = ThisWorkbook.Path 'path to this file
strPriecinokCesta = Left(strPriecinokCesta, Len(strPriecinokCesta) - (Len(strPriecinokCesta) - InStrRev(strPriecinokCesta, "\"))) 'root path is one level above this file
'--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'input files are in a subfolder
strSuborCesta = strPriecinokCesta & "Zdroje\"
strSuborPripona = "Formular_BD_kotolna*.xls" 'name of a file with extension
strSuborNazov = Dir(strSuborCesta & strSuborPripona) 'actual file name
'--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
'get access to the file system
Set oShell = CreateObject("Shell.Application")
Set oDir = oShell.Namespace(strSuborCesta) '<----this will produce an error. In contrast to using a hard coded string. Why?
For Each sFile In oDir.Items '<---- run time error 91 occurs on this line
Debug.Print test & " : " & oDir.GetDetailsOf(sFile, 24) 'comments
Next
Variable strSuborNazov should be a variant
Dim strSuborNazov as variant
oShell.Namespace(strSuborNazov)
https://msdn.microsoft.com/en-us/library/windows/desktop/bb774085(v=vs.85).aspx
Read up on it, couldn't find anything that worked for me.
Basically, I have a file called SourceCode.vb in my resources.
I'm trying to use:
Dim objCodeCompiler As System.CodeDom.Compiler.ICodeCompiler = New VBCodeProvider().CreateCompiler
Dim objCompilerParameters As New System.CodeDom.Compiler.CompilerParameters()
objCompilerParameters.ReferencedAssemblies.Add("System.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll")
objCompilerParameters.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Drawing.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Data.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Deployment.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Xml.dll")
objCompilerParameters.GenerateExecutable = True
objCompilerParameters.GenerateInMemory = False
objCompilerParameters.CompilerOptions = "/target:winexe"
objCompilerParameters.OutputAssembly = "C:\"
Dim strCode As String = My.Resources.SourceCode.ToString
Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, strCode)
If objCompileResults.Errors.HasErrors Then
MsgBox("Error: Line>" & objCompileResults.Errors(0).Line.ToString & ", " & objCompileResults.Errors(0).ErrorText)
Exit Sub
End If
I need it to compile the code and make the file and place it in C:\ - For some reason its not working. Error is:
error: line>0, no input sources specified
Any ideas? Thanks in advance.
Edit: Problem was that I needed to add an actual name for the file after the output. Thanks for the help Hans.
It's actually because you are setting OutputAssembly to a location when it expects an assembly name. It should be:
objCompilerParameters.OutputAssembly = "AssemblyName.exe"
If you want to set the location of the output assembly, add it to your compiler options.
objCompilerParameters.CompilerOptions = "/target:winexe /out:C:\\AssemblyName.exe"
Although, I believe if you want to write to the C: drive, you will need to run your program as administrator.
I'm trying to send a string variable to command prompt using vba excel.
I'm using following code:-
code_name = "xyz.c"
version = "def"
label = "1XDFO"
'open command prompt
Dim oWsc As Object
Set oWsc = CreateObject("WScript.Shell")
Dim oExec As Object
'save config spec in a text file
Set oExec = oWsc.Exec("perl F:\My_work\hello_world.pl code_name version label")
While oExec.Status <> 1 ' Wait for process
Sleep 1000
Wend
While calling perl script at line
"oWsc.Exec("perl F:\My_work\hello_world.pl code_name version label")"
i want to send original contents of string variable code_name,version,label; but its sending the variable names as it is and not the content; Can anyone help me with this?
Thanks in advance.
How can an external script (Perl or any other one) understand that what you are sending are variables and read their content? You have to send just the content:
Set oExec = oWsc.Exec("perl F:\My_work\hello_world.pl " & code_name & " " & version & " " & label)
Clarification 1: VBA or .NET or any other Microsoft language, do not "read variables inside strings", like other languages do, PHP for example.
Clarification 2: even a language capable of reading variables inside strings cannot manage what is being done "outside its framework". If you call a PHP script from an external program, you cannot call it as you are doing now because PHP does not have any control on what the external program does and thus on its variables.