Microsoft Excel: Formula that generates String Content, and Double Quotes - excel-formula

Microsoft Excel: Formula that generates String Content, and Double Quotes
I generate the contents of a batch file in a Microsoft Excel. Then I copy commands to a .BAT file and run the .BAT file.
With each row in the Excel file, I generate a set of BATCH commands, which are currently separated by "&" ... perfectly valid. For example,
The formula:
="#ECHO OFF&cd \users\imemine\&"&"""C:\Program Files (x86)\program\program.exe"" -parameter1 -parameter2 """&A1&""""&"&echo.message"
Output:
#ECHO OFF&cd \users\imemine\&"C:\Program Files (x86)\program\program.exe" -parameter - parameter2 "string"&echo.message
Just for aesthetic reasons, I'd like to replace the "&" with a newline character and have each BATCH command in its own line.
So, I tried to replace the "&" my Excel formula with char(10). I also tried the Alt-Enter character in the formula.
But the output I get has unnecessary double quote characters. For example:
"#ECHO OFF&
cd \users\imemine\&""C:\Program Files (x86)\program\program.exe"" -parameter -parameter2 ""string""&echo.message"
What do I do?
I'd like something like this when I copy the Excel formula result into the BATCH file:
#ECHO OFF
cd \users\imemine\
"C:\Program Files (x86)\program\program.exe" -parameter - parameter2 "string"
echo.message
Thank you, Joanna

I'm not sure that's possible with formulas. We can use as workaround a rectangle shape + [a piece of macro](mandatory, but copy from shape is tedious)
1.Use SUBSTITUTE to replace "&" in your command line.
=SUBSTITUTE(B4,"&",CHAR(10))
2.Create a rectangle shape and link it with the cell containing the new command line.
(select the shape then paste this in the formula bar)
=$B$7
3.Insert the macro. Microsoft Forms 2.0 activated.
Sub ShapeCb()
Dim obj As New DataObject
Dim strText As String
strText = ActiveSheet.Shapes("Rectangle 1").TextFrame.Characters.Text
obj.SetText strText
obj.PutInClipboard
End Sub
Sheet :
Output once copy-pasted:

Related

Excel find and replace function correct formula

I wish to use the find and replace function in excel to remove example sentences from cells similar to this:
text <br>〔「text」text,「text」text〕<br>(1)text「sentence―sentence/sentence」<br>(2)text「sentence―sentence」
Sentences are in between 「」brackets and will include a ― and / character somewhere inside the brackets.
I have tried 「*―*/*」 however this will delete everything from the right of the〔
Is there any way to target and delete these specific sentence brackets, with the find and replace tool?
Desired outcome:
text <br>〔「text」text,「text」text〕<br>(1)text<br>(2)text「sentence―sentence」
Quite a long formula but in Excel O365 you could use:
=SUBSTITUTE(CONCAT(FILTERXML("<t><s>"&SUBSTITUTE(CONCAT(IF(MID(A1,SEQUENCE(LEN(A1)),1)="「","</s><s>「",IF(MID(A1,SEQUENCE(LEN(A1)),1)="」","」</s><s>",MID(A1,SEQUENCE(LEN(A1)),1)))),"<br>","|$|")&"</s></t>","//s[not(contains(., '「') and contains(., '―') and contains(., '/') and contains(., '」'))][node()]")),"|$|","<br>")
As long as you have access to CONCAT you could also do this in Excel 2019 but you'll have to swap SEQUENCE(LEN(A1)) for ROW(A$1:INDEX(A:A,LEN(A1)))
This formula won't work in many cases, but if the string has matching rules as in your example, then try this:
=SUBSTITUTE(C5,"「" & INDEX(TRIM(MID(SUBSTITUTE(","&SUBSTITUTE(C5,"」","「"),"「",REPT(" ",99)),(ROW(A1:INDEX(A1:A100,LEN(C5)-LEN(SUBSTITUTE(C5,"」",""))))*2-1)*99,99)),MATCH("*―*/*",TRIM(MID(SUBSTITUTE(","&SUBSTITUTE(C5,"」","「"),"「",REPT(" ",99)),(ROW(A1:INDEX(A1:A100,LEN(C5)-LEN(SUBSTITUTE(C5,"」",""))))*2-1)*99,99)),0)) & "」","")
explain how it works:
split the string between the characters "「 "and "」" into an array
use match("*―*/*",,0) to find the string position (note that it will only return one value if it exists, if you have multiple strings, you can replace match("*―*/*",) with search ("*―*/*",..) and use it as an extra column to get matches string)
Use the index(array,match("*―*/*",..)) to get the string needs replacing (result)
Replace the original string with the results found =substitute(txt,result,"")
Or,
In B1 enter formula :
=SUBSTITUTE(A1,"「"&TRIM(RIGHT(SUBSTITUTE(LEFT(A1,FIND("」",A1,FIND("/",A1))),"「",REPT(" ",99)),99)),"")
You did not tag [VBA], but if you are not averse, you could write a User Defined Function that would do what you want using Regular Expressions.
To enter this User Defined Function (UDF), alt-F11 opens the Visual Basic Editor.
Ensure your project is highlighted in the Project Explorer window.
Then, from the top menu, select Insert/Module and
paste the code below into the window that opens.
To use this User Defined Function (UDF), enter a formula like =replStr(A1) in some cell.
Option Explicit
Function replStr(str As String) As String
Dim RE As Object
Const sPat As String = "\u300C(?:(?=[^\u300D]*\u002F)(?=[^\u300D]*\u2015)[^\u300D]*)\u300D"
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = True
.Pattern = sPat
replStr = .Replace(str, "")
End With
End Function

Search txt and csv files for string using Excel VBA without opening files

I have a text file that is automatically generated from a machine. The machine writes the txt file in "chunks" (sorry I don't know the exact terminology). I need to pull data from this txt file, but I need the txt file to be finished before pulling data from it. I found a solution to verify that the machine has finished writing to the file... It is not as elegant as i had hoped, but seems to do the trick. Excel VBA opens a command prompt, the command prompt uses a Find command to find the string "End of Report"... This is basically one of the last lines of the txt file and pretty safe to assume the txt file is finished after this is found. This code runs in a loop 1000 times, every 10 seconds, until it finds this string or reaches 1000 tries...
The issue is that "result" returns some other characters besides just "End of Report" this is further complicated by the fact that I am attempting to run this on some csv files too... and "result" returns some additional characters also, but different from the ones returned from the txt files. For example, if I check the length of "result"... The length comes back as 43 on one file and 48 on another file... I think it is counting the file path + "End of Report" + a few more characters?
Anyways, I don't really need the "result"... I really only need a "true" / "false" if "Find" found "End of Report" or not... How can I accomplish this? Is there a different better way to do this? I am not familiar with command prompt programming.
Note: It is important that I search these files without opening them.
Sub test()
Dim SearchStr As String
Dim cmdLine As Object
Dim result As String
Dim FilePath As String
FilePath = "D:\test2.txt"
SearchStr = """End of Report"""
Set cmdLine = CreateObject("WScript.Shell")
result = cmdLine.Exec("%comspec% /C Find " & SearchStr & " " & Chr(34) & FilePath & Chr(34)).STDOut.ReadAll
Debug.Print (result)
End Sub
I am not really an expert in command line, but what I would do is export the result of the FIND command to a file, like here
Then I would check in your VBA code how many rows are in the file (either clean the file before, or check the number of rows before the export is done).
If the number of rows meets the criteria (probably 2 or more rows instead of 1), then you can set the flag to True.

Excel VBA: How to write column name with commercial at "#" in it

I am trying to find out how I should deal with a named column in myTable which contains a commercial at (#) in its name, e.g. active # mail. This code is supposed to print the column number in the Immediate output window:
Sub teststring()
Dim s As String
s = ActiveSheet.Range("myTable[active # mail]").Column
Debug.Print s
End Sub
but it fails. Using .Range("myTable[active" & Chr(64) "& mail]") fails as well.
You can do it like this:
s = ActiveSheet.listobjects("myTable").listcolumns("active # mail").Range.Column
See also https://support.office.com/en-us/article/using-structured-references-with-excel-tables-f5ed2452-2337-4f71-bed3-c8ae6d2b276e for how to escape special characters
So:
s = ActiveSheet.Range("myTable[active '# mail]").Column
will also work.
# has a special meaning in structured references, so you can't use it in a column name without escaping it with ' (a single quote)

Reading each line of a text file into VB

I'm looking to automate some work that I currently have to carry out.
I currently receive a number of machine names that I have to query in unix from config files, but I have to amend the list I receive each day to produce the command. I'm looking for a way to automate this, so I can store the names in a text file and run a script in vb that will automatically produce the command I need to run in unix.
e.g the text file (machines.text) may contain the following:
ABCDE1234
ADEFR1234
BCDFREWE1
each line will be the machine name, but i require this to be changed to lower case and get the following commands output:
grep -i abcdef1234 */*.cfg
grep -i adefr1234 */*.cfg
grep -i bcdfrewe1 */*.cfg
I sometimes get hundreds a day, so looking to shorten the processes as I can just use the original file i receive and not have to manually go through it.
Any suggestions will be much appreciated, even if anyone has any alternatives to VB and excel.
Thanks
you could open the list in Excel, so that all the data to be manipulated goes into Column A, then use formulas as below to create your UNIX commands in Columns B, C, D:
FIRST Command:
="grep -i " &LOWER(LEFT(A:A,FIND(" ",A:A))) & " */*.cfg"
SECOND Command:
="grep -i "&LOWER(LEFT(TRIM(MID(A:A,FIND(" ",A:A),LEN(A:A))),FIND(" ",TRIM(MID(A:A,FIND(" ",A:A),LEN(A:A))))))&" */*.cfg"
THIRD Command:
="grep -i "&LOWER(MID(RIGHT(A:A,LEN(A:A)-FIND(" ",A:A)),FIND(" ",RIGHT(A:A,LEN(A:A)-FIND(" ",A:A))),LEN(RIGHT(A:A,LEN(A:A)-FIND(" ",A:A)))))&" */*.cfg"
Once you have got all your texdt to be manipulated in Column A, copy down the formulas in columns B,C,D
then you could run the below code (may need tweaking) to create your output:
Sub getCommands()
Dim oFso As New Scripting.FileSystemObject
Dim oWriteFile As TextStream
Dim oRange As Range
Set oWriteFile = oFso.CreateTextFile("C:\Commands.txt", True)
Set oRange = Range("B2")
Do Until oRange.Text = ""
With oWriteFile
.WriteLine oRange.Text
.WriteLine oRange.Offset(0, 1).Text ' second command
.WriteLine oRange.Offset(0, 2).Text ' third command
End With
Set oRange = oRange.Offset(1, 0)
Loop
oWriteFile.Close
End Sub

Excel VbScript Quotes issue

I am using Vbscript to write some data into excel then i am saving this excel object as txt file. My problem here is after saving as text file some rows contains quotes ". Below is my code can some body help me recording this.
My Output text file is:
"Rules*V*ZBEA*892**0010*10*IBM-01**"
30,000.00*01/08/2012*21/08/2012****0000013556*01***2600
"Scale value* *********"
problem here is 1st and 3rd row starts and ends with quotes (" ").
code is
Dim objXL1,name
Set objXL1 = CreateObject("Excel.Application")
objXL1.Workbooks.Add
objXL1.Cells(1 ,1) = "Rules*V*ZBEA*892**0010*10*IBM-01** "
objXL1.Cells(2,1) = "30,000.00*01/08/2012*21/08/2012****0000013556*01***2600"
objXL1.Cells(3 ,1) = "Scale value* *********"
name = objXL1.GetSaveAsFilename(,"Text(MS-DOS)(*.txt),*.txt")
objXL1.ActiveWorkbook.SaveAs name ,21 ,,21
objXL1.ActiveWorkbook.Close 0
objXL1.quit
And here once more issue is I am using SaveAs method for getting file name. When execution comes to this line the file save dialog box hiding behind the main IE window is there any way to get this save dialog box in focus?
I assume this is because of the whitespace. In your code there is a trailing whitespace in the frist line.
"Rules*V*ZBEA*892**0010*10*IBM-01** "
-----------------------------------^-
If you would export multiple cells you would need to encapsualte those cells to recognize where a cell value begins and ends.

Resources