VB Script Space - vbscript

I am in need of a vb script that will be used as a macro in excel.
I need the rows with data that have spaces to have the spaces removed. I know how to create a formula one cell at a time but I am clueless on how to do this on a large scale with a looping script. Any help would be appreciated.

Don't know that much about the micros, but in vb-script you can use following code :-
Option Explicit
Dim objFso,strFileName,objFile
Set objFso = CreateObject("Scripting.FileSystemObject")
strFileName="C:\Documents and Settings\amolc\Desktop\test.txt" ''Path of text file
Set objFile = objFso.OpenTextFile(strFileName,1)
strText = objFile.ReadAll
objFile.Close
strText = Replace(strText," ","",vbTextCompare) ''Replace function to remove space
Set objFile = objFso.OpenTextFile(strFileName,2)
objFile.Write (strText)
objFile.Close

Try this code:
Columns("F:F").Select
Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
I try to replace character space (" ") with none ("")

Related

VBscript Replace text with part of filename

I have a directory of files that I want to Loop through and use part of their filename to replace text in a template doc.
For example one filename may be 'NV_AD32_city.dxf'. All files in the directory follow the same filename pattern of XX_XXXX_string.dxf, using two underscores.
I need to capture the string to the right of the first "_" and to the left of the "."so for this example that would be 'AD32_city'
How do I script to use capture that text of the active file to replace text in the template? I guess I need to create an object? But what is the object to use for the current file from a directory?
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Thx for the replies, guys. After several days of trying your code I am just not "getting it". I understand it is set up to take the part of the filename's string that I want but how do I tell the script to use the current file I am looping through? Here is my script so far. I have your code on line 20 under the Sub 'GetNewInputs'
Set fso = CreateObject("Scripting.FileSystemObject")
Option Explicit
Dim WritePath : WritePath = "S:\TempFolder\"
Dim OutFile : OutFile = "VEG_DXF-2-SHP_script-"
Dim WorkingFile : WorkingFile = GetFileContent(SelectFile())
Dim NewState, NewSection, NewArea
Dim OldState, OldSection, OldArea
Call GetNewInputs()
Call GetOldInputs()
Sub GetNewInputs()
NewState = UCase(InputBox("INPUT STATE:", _
"INPUT STATE", "SOCAL"))
NewSection = ("Section_" & InputBox("INPUT SECTION NUMBER:", _
"INPUT SECTION", "14"))
NewArea = "^[^_]+_(.*)\.dxf$"
End Sub
Private Sub GetOldInputs()
OldState = "XX"
OldSection = "_X"
OldArea = "ZZZZ"
End Sub
Function SelectFile()
SelectFile = vbNullString
Dim objShell : Set objShell = WScript.CreateObject("WScript.Shell")
Dim strMSHTA : strMSHTA = "mshta.exe ""about:" & "<" & "input type=file id=FILE>" _
&"<" & "script>FILE.click();new ActiveXObject('Scripting.FileSystemObject')" _
&".GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" & "/script>"""
SelectFile = objShell.Exec(strMSHTA).StdOut.ReadLine()
If SelectFile = vbNullString Then
WScript.Echo "No file selected or not a text file."
WScript.Quit
End If
End Function
Private Function GetFileContent(filePath)
Dim objFS, objFile, objTS
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.GetFile(filePath)
Set objTS = objFile.OpenAsTextStream(1, 0)
GetFileContent = objTS.Read(objFile.Size)
Set objTS = Nothing
End Function
For Each FileRefIn fso.GetFolder("S:\SOCAL\Section_14\Veg DXFs\").Files
NewFile = WorkingFile
NewFile = Replace(NewFile, OldState, NewState)
NewFile = Replace(NewFile, OldSection, NewSection)
NewFile = Replace(NewFile, OldArea, NewArea)
WriteFile NewFile, WritePath & OutFile & ".gms"
WScript.Echo NewArea
Next
Private Sub WriteFile(strLine,fileName)
On Error Resume Next
Dim objFSO, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Do Until IsObject(objFile)
Set objFile = objFSO.OpenTextFile(fileName, 8, True)
Loop
objFile.WriteLine strLine
objFile.Close
End Sub
Well, that’s actually two questions.
To enumerate files in a directory, you can use FileSystemObject, like this (untested)
const strFolderPath = "C:\Temp\Whatever"
set objFSO = CreateObject( "Scripting.FileSystemObject" )
set objFolder = objFSO.GetFolder( strFolderPath )
set colFiles = objFolder.Files
for each objFile in colFiles
' Do whatever you want with objFile
next
Here's the reference of those objects properties/methods.
And to extract portion of file names, you could use a regular expression.
Here’s some guide how to use'em in VBScript.
The following expression should work for you, it will capture the portion of that file names you asked for:
"^[^_]+_(.*)\.dxf$"
If you need to edit the content of the .dxf files, you will need to work within the AutoCAD VBA (Visual Basic for Applications) environment.
If that is the case, you will need to start with something like below:
GetObject("AutoCAD.Application.20")
CreateObject("AutoCAD.Application.20")
https://knowledge.autodesk.com/search-result/caas/CloudHelp/cloudhelp/2015/ENU/AutoCAD-ActiveX/files/GUID-0225808C-8C91-407B-990C-15AB966FFFA8-htm.html
** Please take note that "VBA is no longer distributed with the AutoCAD installation; it must be downloaded and installed separately. The VBA Enabler for Autodesk AutoCAD can be downloaded here."

Exception to overwrite

I have a VBScript - if I run it I do not want it repeating the words it is replacing. Is there an If statement I can add to stop it doing this?
Option Explicit
Const ForReading = 1
Const ForWriting = 2
Dim objFSO,objFile,strText,strNewText
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\newtons\Desktop\Text.txt",ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "<Jim","<!--<Jim")
'<pseudocode>
IF "<!--<Jim" = EXIST THEN DO NOTHING
END IF
'</pseudocode>
Set objFile = objFSO.OpenTextFile("C:\Users\newtons\Desktop\Text.txt",ForWriting)
objFile.WriteLine strNewText
objFile.Close
set objFSO = Nothing
set objFile =
Replace <Jim with <!--Jim instead of <!--<Jim to avoid repeated replacements (i.e. make sure that your search string isn't a substring of your replacement string).
You can use InStr() to check whether strText contains "Jim" or "James" and do or don't replace or save according to what you really want to achieve.
The docs for Replace() explain how to restrict the number of substitutions - if that's what your "execption"/"repeating" is hinting at.
Demo:
>> WScript.Echo Replace("AA", "A", "a", 1, 1, vbTextCompare)
>>
aA
>>

VBScript Renaming File Code Issue

I wrote a simple vbscript to rename files in a particular folder. Specifically to remove particular content from the filname.
The Script I wrote (listed below) runs fine but the highlighted part (second IF-THEN statement) doesn't run. I can't figure out whats wrong with the code. I plan to add more IF-THEN statement to remove particular content from file names.
I'm a novice at this so please be patient with me. Can anyone help?
Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder="C:\Users\Admin2\Downloads\Compressed"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
strFileName = strFile.Name
If InStr(strFileName,"(2014)") > 0 Then
strNewFileName = Replace(strFileName,"(2014)","")
strFile.Name = strNewFileName
End If
**If InStr(strFileName,"(digital)") > 0 Then
strNewFileName = Replace(strFileName,"(digital)","")
strFile.Name = strNewFileName
End If**
Next
Type prefix fraud detected:
For Each strFile In objFolder.Files
"strFile" should be "objFile". Dangerous extra variable in:
strFileName = strFile.Name
The variable "strFileName" will get stale if you change "objFile.Name". Use a variable to hold the new/desired name instead.
strNewFileName = objFile.Name
Renaming the file twice will loose changes on the way. Modify "strNewFileName" (in steps or all at once:
strNewFileName = Replace(Replace(strNewFileName, "(2014)", ""), "(digital)", "")
; you don't really need the If guard, because Replace won't change strings that don't contain the target).
Check for .FileExists(strNewFileName) before you do the rename.
Can you prove that there are file names that contain "(digita1)" <-- mark the digit 1) exactly? Lower vs. upper case? A nasty blank?
I hope the following code helps
Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder="pathtofolder"
Set objFolder = objFS.GetFolder(strFolder)
For Each objFile In objFolder.Files
ObjFileName = ObjFile.Name
NewFileName = Replace(Replace(ObjFileName,"(2014)",""),"(digital)","")
Set fileSystemObject = CreateObject("Scripting.FileSystemObject")
If fileSystemObject.FileExists(NewFileName) Then
Else
ObjFile.Name = Trim(NewFileName)
End If
Next

VBS replace and write

Start of that I'm not that good with VBS but trying to learn.
Right now I have some difficulties with writing replace to a text file.
What I want to do is to search for the text "VGML", when this is found check on same row if there is a "STML" if so, this should replaced with " " to not mess up the positions in the file. And finally, if "VGML" is found without the "STML", the "VGML" should be removed.
I got so far when using echo I can see that the code does what I want, but writing to file mostly get me a empty file where the code removed everything.
Could anyone put me in the correct direction?
Here is the code:
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Script\RemoveSTML\testFiles\test.txt", ForReading)
strEMTY = " "
strSTML = "STML"
strVGML = "VGML"
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If InStr(strLine,strVGML)>0 Then
If Instr(strLine,strSTML)>0 Then
strLine = Replace(strLine, strSTML, strEMTY)
wscript.Echo strLine
Else
strLine = Replace(strLine, strVGML, strEMTY)
wscript.Echo strLine
End If
End If
Loop
objFile.Close
Set objFile = objFSO.OpenTextFile("C:\Script\RemoveSTML\testFiles\test.txt", ForWriting)
objFile.Write strLine
objFile.Close
Wscript.Echo "done"
Thanks for your help! For giving me a kick in the correct direction!
In the loop, you read each line of the file and you write it into the variable strLine.
After that, you replace "SMTL"/"VGML", but after that, you're doing nothing with the content of strLine - you just replace it with the next line from the source file in the next loop.
Only at the end, you write strLine to the file once - but in that moment, strLine contains only the last line from the source file.
Solution: you can either write into the destination file inside the Do...Loop (but I'm not familiar with VBScript, so I don't know if/how to do this) or you can use a second string variable where you append strLine inside the loop but after the replacing...like this:
strFinal = strFinal & strLine
At the end, you write strFinal to the file, not strLine.

VBScript remove newline

I have an HTML page with one or more newlines after </html>. My VBScript file is able to find the replace the newlines with emptiness. But, it looks like OpenTextFile is putting a newline at the end again. Help!
'Pulled this from the InterWebs
Const ForReading = 1 Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("a.html", ForReading)
strText = objFile.ReadAll
'Wscript.Echo strText
objFile.Close
strNewText = Replace(strText, "</html>" & vbCrlf, "</html>")
Set objFile = objFSO.OpenTextFile("a.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close
Instead of objFile.WriteLine strNewText use objFile.Write strNewText. This will write the file without a newline at the end.
BTW, another way of removing the newline(s) from after your </html> tag would be strNewText = Trim(strText) instead of using Replace()
This may help:
The TextStream object has the following important methods for writing to text files:
Write(string) - Writes a string to the open text file.
WriteLine(string) - Writes a string to the text file and finishes it off with the new line character.
WriteBlankLines(lines) - Writes a specified number of new line characters.
If you do not want a newline at the end, use
objFile.Write strNewText
instead of
objFile.WriteLine strNewText
Your code is mostly correct. It's not OpenTextFile that's adding a newline, it's WriteLine. If you replace that with Write, it will work as you expect.

Resources