vbscript to display output upto the blank line - vbscript

My txt file1 is
Fruits
-------
Apple
Banana
Orange
Vegetables
---------
broccoli
Beans
txtfile 2
Fruits
Vegetables
output should be:
Banana
Orange
Brocoli
Beans
I should be able to grab from ------- to blank space and I am having problems in doing that.

I think the following code might give you some idea about reading txt files,
Set fso = CreateObject("Scripting.FileSystemObject")
strWholeData = fso.OpenTextFile("C:\...\xxx.txt").ReadAll
strDataArr = Split(Trim(strWholeData),vbNewLine)
For di = Lbound(strDataArr) To Ubound(strDataArr)
Msgbox strDataArr(di)
Next

Related

WMI Query Output to variable [duplicate]

I can't get the following function in VBScript to work. I am trying to get all of the files in a folder and loop through them to get the highest numbered file. (file name format is log_XXX.txt) The problem that I am having is that the code never enters my For Each loop. I am new to VBScript, but I don't seem to understand why this won't work.
Function GetFileNumber(folderspec)
Dim fso, f, f1, fc, s, tempHighNum
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
WScript.Echo f.Files.Count : rem prints 3
Set fc = f.Files
WScript.Echo fc.Count : rem prints 3
Set tempHighNum = "000"
For Each f1 in fc
WScript.Echo f1.Size : rem does not print
WScript.Echo f1.Type : rem does not print
WScript.Echo f1.Name : rem does not print
s = Right(f1.name,3)
IF NOT(ISNULL(s)) THEN
IF (s > tempHighNum) THEN
tempHighNum = s
END IF
END IF
Next
GetFileNumber = tempHighNum
End Function
Change this line:
Set tempHighNum = "000"
to the following:
tempHighNum = "000"
You are attempting to set the tempHighNum variable to a string type. Therefore, you should not use the Set keyword. Set is only needed when assigning object types to variables.
I am not sure how your script works so I put this HTML application together for you. It uses a batch file called Dir.Bat located in C:\Batch which makes a file called Data.Txt located in c:\Temp. Then the script takes
over. The script reads the file Data.Txt line by line. As each line is read two split statements are used to separate out the string in the text file's name. After that I collect those strings containing numbers into the variable ListCol as I test for larger and larger numbers. I finally wind up with the largest number which I place in your original variable tempHighNum. I will post the HTA file and the Dir.Bat file. I know I did not write the script as a function using a parameter so if you really need to use a parameter, I will try to help you by changing the HTA file to make it possible to enter the path and file name in a TextBox. That should make it easy to
change and use. I added and changed a thing or two to make it run smoother.
I am not sure how your script works so I put this HTML application together for you. It uses a batch file called Dir.Bat located in C:\Batch which makes a file called Data.Txt located in c:\Temp. Then the script takes
over. The script reads the file Data.Txt line by line. As each line is read two split statements are used to separate out the string in the text file's name. After that I collect those strings containing numbers into the variable ListCol as I test for larger and larger numbers. I finally wind up with the largest number which I place in your original variable tempHighNum. I will post the HTA file and the Dir.Bat file. I know I did not write the script as a function using a parameter so if you really need to use a parameter, I will try to help you by changing the HTA file to make it possible to enter the path and file name in a TextBox. That should make it easy to
change and use. I added and changed a thing or two to make it run smoother.
<HTML><!-- C:\HTML_and_HTA_CODE_EXAMPLES\ATest.Hta -->
<HEAD>
<TITLE>ATest.Hta</TITLE>
<HTA:APPLICATION ID="HTA MyApp"
APPLICATIONNAME="Help4Saul Dolgin"
BORDER ="thick"
BORDERSTYLE ="complex"
CAPTION ="yes"
CONTEXTMENU ="no"
ICON ="http://Your URL/your icon.ico"
INNERBORDER ="yes"
MAXIMIZEBUTTON ="yes"
MINIMIZEBUTTON ="yes"
NAVIGABLE ="no"
SCROLL ="no"
SHOWINTASKBAR ="yes"
SINGLEINSTANCE ="yes"
SYSMENU ="yes"
VERSION ="1.0"
WINDOWSTATE ="Normal"/>
</HEAD>
<style>
.ExBt21 {background:"#E0E0E0";Color:"red";}/* For Exit Button */
.Spn4 {font-family:"arial";font-weight:"bold";Color:"blue"}
.Spn2 {Color:"red"}
.tAr1 {font-family:"arial";font-weight:"bold";Color:"blue"}
</style>
<SCRIPT Language="VBScript">
Sub GetFileNumber
Dim FSO, f, fc, tempHighNum, strLine, objSHO, line
Dim DataArr, Data1Arr, Data2Arr, ListCol
fc=""
ListCol=""
tempHighNum=000
Set objSHO=CreateObject("WScript.Shell")
objSHO.run "C:\Batch\Dir.bat"
Set FSO = CreateObject( "Scripting.FileSystemObject" )
Set f = FSO.OpenTextFile("c:\Temp\Data.Txt", "1")
Do Until f.AtEndOfStream
fc = fc & f.ReadLine & vbLf
Loop
tArea1.innerHTML=fc
Data1Arr = Split(fc,vbLf)
Count=UBound(Data1Arr)
For x=0 To Count
DataArr = Split(Data1Arr(x),".")
If x <= Count-1 Then
Data2Arr = Split(DataArr(0),"_")
ListCol = ListCol & Data2Arr(1) & vbLf
If Data2Arr(1) > tempHighNum Then
tempHighNum = Data2Arr(1)
End If
End If
Next
Span2.innerHTML=tempHighNum
End Sub
Sub ExtBtn:Window.close:End Sub' Exit Script For Window
</SCRIPT>
<BODY bgcolor="#D0D0D0">
<button OnClick="GetFileNumber">Button To Press</button><br/>
<span id="Span1" class="Spn1">The biggest No. is: </span><span id="Span2" class="Spn2"></span><br/><br/>
<span Id="Span3" Class="Spn3">Dir.Bat looks in: </span><span Id="Span4" Class="Spn4">C:\Temp\Log_???.Txt</span><br/>
<textarea Id="tArea1" class="tAr1" rows="10"></textarea><br/><br/>
<input id="ExBtn21" class="ExBt21" type="Button" name="ExitBtn21" OnClick="ExtBtn" value="&nbsp-Exit-&nbsp"/><!-- Exit Button -->
</BODY>
</HTML>
The Dir.Bat file is next:
#Echo Off
Dir/B c:\Temp\Log_???.Txt>c:\Temp\Data.Txt

Trouble copying text file into Excel using VBA

I want to copy contents from text file to an Excel cell using VBA. I can do this succesfully from most text files. But in case of certain files, the code is copying only partial data into the excel file.
This is the code I used for copying
FileName = folderpath & sFile
Set mytextfile = Workbooks.Open(FileName)
mytextfile.Sheets(1).Cells.CurrentRegion.Copy ThisWorkbook.Sheets("RawData").Range("A" & inputRow)
'mytextfile.Sheets(1).Range("A1").CurrentRegion.Copy ThisWorkbook.Sheets("RawData").Range("A" & inputRow)
mytextfile.Close (False)
I already understand what is the problem. While opening certain text files as excel files, some contents are present in cell A1 and the rest in cell A2.
I don't know why it is opened so. I am posting contents of two text file below:
1)Text file whose contents are contained in different cells when opened in excel
fwi!3F5A!041!g1ksIpqub7J MCMILLAN J. PIIKKILA RAYMONDBERRY#WEBTV.NET
+001 061 477 130 F g3ktHqrwc9 CLE!g1ksIpqub7 CLEHS04C |P.O. BOX 171 SEARSPORT,ME Nashville 68800 AZ| |5150 CTY RD 525 Raleigh 64292|
18000000 0412CL0 1 N 2
I got the following output when I used the above text file.
fwi!3F5A!041!g1ksIpqub7J MCMILLAN J. PIIKKILA RAYMONDBERRY#WEBTV.NET +001 061 477 130 F g3ktHqrwc9 CLE!g1ksIpqub7 CLEHS04C |P.O. BOX 171 SEARSPORT
2)Text file whose contents are contained in a single cell A1
fSj!3U68!071!gQloo3d5OGG Presley Y. TART JR PULPACTION82#HOIMAIL.COM
+001 047 475273 M gQmqq6d8ME CVE!gQloo3d5OG CVEGF07C |10001 SW 125TH CT RD Reno 88595 TN| |10849 DEBORAH DRIVE Glendale 70958| 97400000
0712CV0 0 N 0
I got the following output when I used the above text file.
fSj!3U68!071!gQloo3d5OGG Presley Y. TART JR PULPACTION82#HOIMAIL.COM +001 047 475273 M gQmqq6d8ME CVE!gQloo3d5OG CVEGF07C |10001 SW 125TH CT RD Reno 88595 TN| |10849 DEBORAH DRIVE Glendale 70958| 97400000 0712CV0 0 N 0
There is no apparent difference between the contents of these two file.
I also tried this code but without any success:
FileName = folderpath & sFile
Set mytextfile = Workbooks.Open(FileName)
mytextfile.Sheets(1).Range("A1").CurrentRegion.Copy ThisWorkbook.Sheets("RawData").Range("A" & inputRow)
mytextfile.Close (False)
Problem:
You are not using the right approach to read a *.txt file in VBA. Opening file using Workbooks.Open() treats the opened file as a *.csv. Therefore, when Excel is reading a stream and a comma occurs it treats it as a new line separator and throws the remaining part (after the comma) to the next cell. As stated on MSDN Workbooks.Open Method
expression .Open(FileName ... )
expression A variable that represents a Workbooks object.
Clearly, a Workbook object not a txt file.
Solution:
The right approach to read content of a *.txt file is to use the FileSystemObject and TextStream objects from the Microsoft Scripting Runtime Library.
I wrote a simple Sub for you that reads the entire content of a *.txt file. In order to make it work you have to add references to your project
In VBE window, click Tools » References » scroll down, find, and tick Microsoft Scripting Runtime
Now, screen through the below code and modify the path to your *.txt file or pass the path through a parameter and the entire content of your *.txt file will be placed in the first Sheet Sheet(1) Cell A1
Sub ReadTxtFile()
Dim oFSO As New FileSystemObject
Dim oFS As TextStream
Dim fileName As String
' make sure to update your path or
' pass it to the sub through parameter
fileName = "C:\Users\fooboo\Desktop\text.txt"
Set oFS = oFSO.OpenTextFile(fileName)
Dim content As String
content = oFS.ReadAll
With Sheets(1).Range("A1")
.ClearContents
.NumberFormat = "#"
.Value = content
End With
oFS.Close
Set oFS = Nothing
Set oFSO = Nothing
End Sub

String search with in the excel column values row wise

I have an Excel sheet which has 200 columns. Now number of rows are 3500. So i have to search a string if it presents within any column for each row. Now to make the process fatser,I am looking for any alternate instead of Looping technique. Is there any such?
IntRow6 = 2
DataCount = 0
Do While objSheet6.Cells(IntRow6,1).Value <> ""
For DataCount = 0 to UBound(VMHArray)
IntClmn3 = 1
Do While 1 = 1
If objSheet6.Cells(IntRow6,IntClmn3).Value = VMHArray(DataCount) Then
objSheet6.Cells(IntRow6,IntClmn3+2).Value=objSheet6.Cells(IntRow6,IntClmn3+5).Value
Exit Do
End If
IntClmn3 = IntClmn3 + 1
Loop
Next
IntRow6 = IntRow6 + 1
Loop
The above is taking to much time, thus i am looking for an equivalent VBScript code which can run more faster search.
EDIT:
ParentColmnCount=ParentColmnCount-1
IntRow6=2
DataCount=0
Do While objSheet6.Cells(IntRow6,1).Value <> ""
For DataCount=0 to UBound(VMHArray)
If objSheet6.Range(objSheet6.Cells(IntRow6,1),objSheet6.Cells(IntRow6,ParentColmnCo‌​unt)).Find(VMHArray(DataCount)) <> Nothing Then
MsgBox("Hi")
End If
Next
IntRow6=IntRow6+1
Loop
I'm getting any error saying that, "Object variable not set" error at the Range line of the above code.
UPDATE
I have updated my code as per your suggestion,and modified the declaration of variables as below:
Option Explicit
Dim objExcel1,objWorkbook
Dim strPathExcel1
Dim objSheet6,objSheet3
Dim IntRow6,IntRow3
Dim IntClmn3
Dim DataCount,ParentColmnCount
Dim Falg
Dim TaskCounter
Dim r As Range
Dim s As Variant
But I am getting the error again: Expected end of statement" in the line "Dim r As Range"
Check out Range.Find (which returns a Range object). It's faster than a loop.
Example:
Sub Test()
Dim r As Range
Dim matched As Range
'Get the second row
Set r = Sheet1.Range("2:2")
Set matched = r.Find("myString")
'Do stuff with matched
End Sub
UDPATE:
Assuming you are using CreateObject("Excel.Application"), then the Range object will be present (as CreateObject will return an instance of Excel which contains Range objects and functionality).
For further proof, you're already looping through the worksheet using Range objects (Cells is a Range object).
UPDATE:
Here's a more advanced example. Assume the following data in on Sheet1:
fred ethel ricky bobby 1 2 3 4
lucy myrtle fonzy rickie 1 2 3 4
joanie chachie donna patty 1 2 3 4
selma homer lisa bart 1 2 3 4
You can loop through the ranges like so:
Sub test()
Dim r As Range
Dim names(3) As String
Dim s As Variant
names(0) = "ethel"
names(1) = "fonzy"
names(2) = "patty"
names(3) = "selma"
For Each s In names
For Each r In Sheet1.Cells.CurrentRegion.Find(s)
r.Offset(0, 4).Value = r.Offset(0, 4).Value + 1000
Next r
Next s
End Sub
After the routine is done, the data is now:
fred ethel ricky bobby 1 1002 3 4
lucy myrtle fonzy rickie 1 2 1003 4
joanie chachie donna patty 1 2 3 1004
selma homer lisa bart 1001 2 3 4
UPDATE:
I just saw your comment on your question (and edited your question to include the updated code).
You're getting "Object variable not set" on that line because you cannot use <> comparisons with objects. Change the line to read:
If Not objSheet6.Range(objSheet6.Cells(IntRow6,1),objSheet6.Cells(IntRow6,ParentColmnCo‌​unt)).Find(VMHArray(DataCount)) Is Nothing Then

VBScript to find and move files automatically

I've been tasked with trying to automate a task at work, because we've had issues lately with people remembering to do it.
In general, here's what I need a script to do:
Get the date of the previous day, in the format YYYYMMDD
Enter a folder with that given name
Search within all the folders underneath that location for 4 specific files
Copy those files to several different locations
The issue I'm having is that, for the 4 files I'm looking for, they're located in 2 different folders. 3 in 1, 1 in the other. The names of these folders changes daily, depending on what queue they got put into when generated by some other software. I need these files to be moved so that another script can be run on them. I'm having trouble figuring out how to accomplish this. Anyone have some ideas?
If the folders containing the interesting files are subfolders of your dated directory, you can use a nested loop:
Dim sDFolder : sDFolder = "..\data\20110105"
Dim dicFiNa : Set dicFiNa = CreateObject("Scripting.Dictionary")
dicFiNa("1.txt") = ""
dicFiNa("3.txt") = ""
dicFiNa("5.txt") = ""
Dim oRDir : Set oRDir = goFS.GetFolder(sDFolder)
Dim oSDir
For Each oSDir In oRDir.SubFolders
Dim oFile
For Each oFile In oSDir.Files
WScript.Echo "looking at", oFile.Path
If dicFiNa.Exists(oFile.Name) Then
WScript.Echo "found", oFile.Name, "will copy"
End If
Next
Next
output:
looking at E:\trials\SoTrials\answers\8750206\data\20110105\whatever\6.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\whatever\5.txt
found 5.txt will copy
looking at E:\trials\SoTrials\answers\8750206\data\20110105\unknown\4.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\unknown\3.txt
found 3.txt will copy
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\2.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\1.txt
found 1.txt will copy
A full recursive walk would be a bit more complex, so say so, if you need it.
Just for fun: a recursive version:
Dim sDFolder : sDFolder = "..\data\20110105"
Dim dicFiNa : Set dicFiNa = CreateObject("Scripting.Dictionary")
dicFiNa("1.txt") = ""
dicFiNa("3.txt") = ""
dicFiNa("55.txt") = ""
Dim oRDir : Set oRDir = goFS.GetFolder(sDFolder)
walk oRDir, dicFiNa, "whatever you need to copy the files"
Sub walk(oDir, dicFiNa, vCargo)
Dim oItem
For Each oItem In oDir.Files
WScript.Echo "looking at", oItem.Path
If dicFiNa.Exists(oItem.Name) Then
WScript.Echo "found", oItem.Name, "will copy"
End If
Next
For Each oItem In oDir.SubFolders
walk oItem, dicFiNa, vCargo
Next
End Sub
output:
looking at E:\trials\SoTrials\answers\8750206\data\20110105\whatever\6.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\whatever\5.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\unknown\4.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\unknown\3.txt
found 3.txt will copy *
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\2.txt
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\1.txt
found 1.txt will copy *
looking at E:\trials\SoTrials\answers\8750206\data\20110105\puzzle\deep\deeper\55.txt
found 55.txt will copy *
(*) as soon as the permission problem is solved.

VBScript For Each isn't working

I can't get the following function in VBScript to work. I am trying to get all of the files in a folder and loop through them to get the highest numbered file. (file name format is log_XXX.txt) The problem that I am having is that the code never enters my For Each loop. I am new to VBScript, but I don't seem to understand why this won't work.
Function GetFileNumber(folderspec)
Dim fso, f, f1, fc, s, tempHighNum
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
WScript.Echo f.Files.Count : rem prints 3
Set fc = f.Files
WScript.Echo fc.Count : rem prints 3
Set tempHighNum = "000"
For Each f1 in fc
WScript.Echo f1.Size : rem does not print
WScript.Echo f1.Type : rem does not print
WScript.Echo f1.Name : rem does not print
s = Right(f1.name,3)
IF NOT(ISNULL(s)) THEN
IF (s > tempHighNum) THEN
tempHighNum = s
END IF
END IF
Next
GetFileNumber = tempHighNum
End Function
Change this line:
Set tempHighNum = "000"
to the following:
tempHighNum = "000"
You are attempting to set the tempHighNum variable to a string type. Therefore, you should not use the Set keyword. Set is only needed when assigning object types to variables.
I am not sure how your script works so I put this HTML application together for you. It uses a batch file called Dir.Bat located in C:\Batch which makes a file called Data.Txt located in c:\Temp. Then the script takes
over. The script reads the file Data.Txt line by line. As each line is read two split statements are used to separate out the string in the text file's name. After that I collect those strings containing numbers into the variable ListCol as I test for larger and larger numbers. I finally wind up with the largest number which I place in your original variable tempHighNum. I will post the HTA file and the Dir.Bat file. I know I did not write the script as a function using a parameter so if you really need to use a parameter, I will try to help you by changing the HTA file to make it possible to enter the path and file name in a TextBox. That should make it easy to
change and use. I added and changed a thing or two to make it run smoother.
I am not sure how your script works so I put this HTML application together for you. It uses a batch file called Dir.Bat located in C:\Batch which makes a file called Data.Txt located in c:\Temp. Then the script takes
over. The script reads the file Data.Txt line by line. As each line is read two split statements are used to separate out the string in the text file's name. After that I collect those strings containing numbers into the variable ListCol as I test for larger and larger numbers. I finally wind up with the largest number which I place in your original variable tempHighNum. I will post the HTA file and the Dir.Bat file. I know I did not write the script as a function using a parameter so if you really need to use a parameter, I will try to help you by changing the HTA file to make it possible to enter the path and file name in a TextBox. That should make it easy to
change and use. I added and changed a thing or two to make it run smoother.
<HTML><!-- C:\HTML_and_HTA_CODE_EXAMPLES\ATest.Hta -->
<HEAD>
<TITLE>ATest.Hta</TITLE>
<HTA:APPLICATION ID="HTA MyApp"
APPLICATIONNAME="Help4Saul Dolgin"
BORDER ="thick"
BORDERSTYLE ="complex"
CAPTION ="yes"
CONTEXTMENU ="no"
ICON ="http://Your URL/your icon.ico"
INNERBORDER ="yes"
MAXIMIZEBUTTON ="yes"
MINIMIZEBUTTON ="yes"
NAVIGABLE ="no"
SCROLL ="no"
SHOWINTASKBAR ="yes"
SINGLEINSTANCE ="yes"
SYSMENU ="yes"
VERSION ="1.0"
WINDOWSTATE ="Normal"/>
</HEAD>
<style>
.ExBt21 {background:"#E0E0E0";Color:"red";}/* For Exit Button */
.Spn4 {font-family:"arial";font-weight:"bold";Color:"blue"}
.Spn2 {Color:"red"}
.tAr1 {font-family:"arial";font-weight:"bold";Color:"blue"}
</style>
<SCRIPT Language="VBScript">
Sub GetFileNumber
Dim FSO, f, fc, tempHighNum, strLine, objSHO, line
Dim DataArr, Data1Arr, Data2Arr, ListCol
fc=""
ListCol=""
tempHighNum=000
Set objSHO=CreateObject("WScript.Shell")
objSHO.run "C:\Batch\Dir.bat"
Set FSO = CreateObject( "Scripting.FileSystemObject" )
Set f = FSO.OpenTextFile("c:\Temp\Data.Txt", "1")
Do Until f.AtEndOfStream
fc = fc & f.ReadLine & vbLf
Loop
tArea1.innerHTML=fc
Data1Arr = Split(fc,vbLf)
Count=UBound(Data1Arr)
For x=0 To Count
DataArr = Split(Data1Arr(x),".")
If x <= Count-1 Then
Data2Arr = Split(DataArr(0),"_")
ListCol = ListCol & Data2Arr(1) & vbLf
If Data2Arr(1) > tempHighNum Then
tempHighNum = Data2Arr(1)
End If
End If
Next
Span2.innerHTML=tempHighNum
End Sub
Sub ExtBtn:Window.close:End Sub' Exit Script For Window
</SCRIPT>
<BODY bgcolor="#D0D0D0">
<button OnClick="GetFileNumber">Button To Press</button><br/>
<span id="Span1" class="Spn1">The biggest No. is: </span><span id="Span2" class="Spn2"></span><br/><br/>
<span Id="Span3" Class="Spn3">Dir.Bat looks in: </span><span Id="Span4" Class="Spn4">C:\Temp\Log_???.Txt</span><br/>
<textarea Id="tArea1" class="tAr1" rows="10"></textarea><br/><br/>
<input id="ExBtn21" class="ExBt21" type="Button" name="ExitBtn21" OnClick="ExtBtn" value="&nbsp-Exit-&nbsp"/><!-- Exit Button -->
</BODY>
</HTML>
The Dir.Bat file is next:
#Echo Off
Dir/B c:\Temp\Log_???.Txt>c:\Temp\Data.Txt

Resources