Find and replace string in a file using batch script

I am writing a batch script to replace " ", with " ". The below code works but it prefixes each line with the line number and :.
It is the last part of the line that I am trying to replace.
E.g.
" ","BALANCE_SHEET ","ASSETS ","03","LEVEL_2 ",Asset Accounts," ",
To be replaced as
" ","BALANCE_SHEET ","ASSETS ","03","LEVEL_2 ",Asset Accounts," "
Code:
@echo off &setlocal
set "search=" ","
set "replace=" ""
set "textfile=Build_Accounts_Plan_Source.txt"
set "newfile=Build_Accounts_Plan_Source_new.txt"
(for /f "delims=" %%i in ('findstr /n "^" "%textfile%"') do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:%search%=%replace%!"
echo(!line!
endlocal
))>"%newfile%"
type "%newfile%"
Output:
3:" ","BALANCE_SHEET ","ASSETS ","03","LEVEL_2 ",Asset Accounts," "
Regards,
Ragav.

Did you retype the code or did you use copy/paste? Retyping is not a good idea.
You can do this to find the cause of the problem:
Run the modified code below.
Use notepad.exe to open the file TempVBS.vbs in your %temp% folder.
Mark & copy the code, then paste it into your reply.
@echo off
set "textfile=Build_Accounts_Plan_Source.txt"
set "newfile=Build_Accounts_Plan_Source_new.txt"
set Scr="%temp%\TempVBS.vbs"
(  echo Set oFSO = CreateObject("Scripting.FileSystemObject"^)
   echo Set oInput = oFSO.OpenTextFile(WScript.Arguments(0^), 1^)
   echo sData = Replace(oInput.ReadAll, "," ^& VbCrLf, VbCrLf^)
   echo Set oOutput = oFSO.CreateTextFile(WScript.Arguments(1^), True^)
   echo oOutput.Write sData
   echo oInput.Close
   echo oOutput.Close) > %Scr%
cscript //nologo %Scr% %textfile% %newfile%

Similar Messages

  • Search and replace strings in a file while ignoring substrings

    Hi:
    I have a java program that searches and replaces strings in a file. It makes a new copy of the file, searches for a string in the copy, replaces the string and renames the new copy to the original file, thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but searching for "Topabcd" and replacing it doesnot work because there is a match for "abcd" in a different search scenario. How can I modify the code such that if "abcd" is already searched and replaced then it should not be searched for again or rather search for "abcd" as entire string and not if its a substring of another string.
    In the below code output, all instances of "abcd" and the ones of "Topabcd" are replaced by ABCDEFG and TopABCDEF respectively, whereas according to the desired output, "abcd" should be replaced by ABCDEFG and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
              String find_productstring = "abcd";
              String replacement_productstring = "ABCDEFG";
              compsXml = new FileReader(compsLoc);
              compsConfigFile = new BufferedReader(compsXml);
              File compsFile =new File("file.xml");
              File compsNewFile =new File("file1.xml");
              BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
              while ((compsLine = compsConfigFile.readLine()) != null)
                    new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
                    out.write(new_compsLine);
                    out.write("\n");
                out.close();
                compsConfigFile.close();
                compsFile.delete();
                compsNewFile.renameTo(compsFile);
            catch (IOException e)
            //since "Topabcd" contains "abcd", which is the search above and hence the string "Topabcd" is not replaced correctly
             try
                   String find_producttopstring = "Topabcd";
                   String replacement_producttopstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
                   compsConfigFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
                   BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
                   while ((compsLine = compsConfigFile.readLine()) != null)
                         new_compsLine =compsLine.replaceFirst(find_producttopstring, replacement_producttopstring);
                         out.write(new_compsLine);
                         out.write("\n");
                     out.close();
                     compsConfigFile.close();
                     compsFile.delete();
                     compsNewFile.renameTo(compsFile);
                 catch (IOException e)
            }Thanks a lot!

    Hi:
    I have a java program that searches and replaces
    strings in a file. It makes a new copy of the file,
    searches for a string in the copy, replaces the
    string and renames the new copy to the original file,
    thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but
    searching for "Topabcd" and replacing it doesnot work
    because there is a match for "abcd" in a different
    search scenario. How can I modify the code such that
    if "abcd" is already searched and replaced then it
    should not be searched for again or rather search for
    "abcd" as entire string and not if its a substring of
    another string.
    In the below code output, all instances of "abcd" and
    the ones of "Topabcd" are replaced by ABCDEFG and
    TopABCDEF respectively, whereas according to the
    desired output, "abcd" should be replaced by ABCDEFG
    and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
    String find_productstring = "abcd";
    String replacement_productstring = "ABCDEFG";
    compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    BufferedReader(compsXml);
    File compsFile =new File("file.xml");
    File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    FileWriter("file1.xml"));
    while ((compsLine =
    compsConfigFile.readLine()) != null)
    new_compsLine
    =compsLine.replaceFirst(find_productstring,
    replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
    catch (IOException e)
    //since "Topabcd" contains "abcd", which is
    the search above and hence the string "Topabcd" is
    not replaced correctly
    try
                   String find_producttopstring = "Topabcd";
    String replacement_producttopstring =
    topstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    gFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    dWriter(new FileWriter("file1.xml"));
    while ((compsLine =
    compsLine = compsConfigFile.readLine()) != null)
    new_compsLine
    new_compsLine
    =compsLine.replaceFirst(find_producttopstring,
    replacement_producttopstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
                 catch (IOException e)
    Thanks a lot!I tried the matches(...) method but it doesnt seem to work.
    while ((compsLine = compsConfigFile.readLine()) != null)
    if(compsLine.matches(find_productstring))
         System.out.println("Exact match is found for abcd");
         new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
         else
         System.out.println("Exact match is not found for abcd");
         out.write(compsLine);
         out.write("\n");

  • Find and replace string in file

    hi,
    i need to find and replace text (string) data in about 100+ files, i've decided to write a small java program to do it but i'm stuck on how to replace.
    here is what i'm heading towards:
    class ReplaceString {
      BufferedReader in;
      BufferedReader os;
      public static void main(String args[]) {
        ReplaceString obj = new ReplaceString();
        obj.replace();
       void replace() {
         try {
           in = new BufferedReader(new FileReader("a.txt");
           os = new BufferdWriter(new FileWriter("a.txt");
           //  read until end of file
           String currentLine = new String();
           while((currenLine=is.readLine()) != null) {
             //  if matching text then replace????
             if(currentLine.equals("Version 001") {
                // how to now replace the Version 001 with Version 002???
         }catch(IOException e) {
            System.out.println(e);
            in.close();
            os.close();
         in.close();
         os.close();
    }the above code i just typed so there might be errors, but looks ok to me, is there any way once i find the string i want to replace, to replace the string with another string. basically i want to replace all occurrences of the text "Version 001" with "Version 002"
    Thank you.

    Is it always true, as in your example, that the replacement is the same length as the existing string? If so, this one's easy.
    Is it also true that you don't need to worry about 16-bit chars? (Again, as in your example.) If you're using just ASCII characters, this gets easier still.
    1) Segregate the file I/O from the search/replace process.
    2) Main becomes:
    readFile();
    replace( "this", "that" );
    writeFile();Use a byte array buffer, defined in your main class. Fill it via the readFile() code. Use a RandomAccessFile, check its length() to allocate your byte array, then do a single read() to fill the buffer.
    A brute force search will certainly work: scan for the first search character, then check the rest for a match, replace if you've got a match and continue scanning. Alternative if your file's aren't too big: create a String from the byte array:
    // buffer is a byte array
    String s = new String( buffer );And use the String.replaceAll() to do the search/replace. Recover the buffer with:
    buffer = string.getBytes();A single write() and close() should handle the remaining work.

  • How do I find and replace text in PHP files?

    How can I in CS3 make sitewide changes to the text in PHP pages without changing variable names etc that have the same name?
    For example if I have an installation of a PHP forum and I want to change every instance of the word 'forum' to 'message board'...
    If I used the 'inside tag' search with " as the tag, then if "" contained a variable called 'forum' it would also be changed and therefore corrupt the code....
    Is there a simple way around this?
    Thanks!
    I'm using CS3 on Windows Vista.

    It looks like you're trying to find and replace source code, so you may be able to look at the various places that are looked at when finding and uncheck the ones that don't apply.
    But, if it's all source code then that won't help.  One thing that may work is to expand the search option - for example if the work "forum" that you're wanting to change it preceded by another word, or character or something that sets it apart, then do you find on that. You can expand that search phrase as far out in either direction that you need to to make it different, if of course that is practical in your situation.
    The only other way I can think of is to somehow create an exception rule, but I'm not sure if that's possible or how to do it.

  • In the new Numbers, can I find and replace within formulas like I used to in Numbers'09?

    I use Numbers with quite long formulas with reference to other tables. With Numbers'09, it was extremely useful to copy formulas and then use "find and replace" to change the terms within.
    Did they remove this option? I don't seem to be able to do that with the new Version.
    If it's still there, where do I find it?
    If it's not there.... why would they remove it.
    Thanks

    Basically, I use it for payroll, taxes, and so on... I have one sheet per employee (which compiles their weekly payroll). I have then different sheets which makes the quarterly taxes calculation (state and federal taxes - 941, 940, W2, disability,  UI, paystubs, tracks payments and deadlines, etc... ). It took me awhile to write all of the formulas, but now it does everything for me.
    When I add an employee. I have to add a sheet, but also add a line in the calculation sheets. Because all the employee sheets are the same format, all I need to do (or used to now) was to copy the line above, and just change the reference name of the employee sheet  within the formula (because there are several terms that are looked up, the reference name comes several time in the formula)... changing it manually is really annoying. What was taking me a minute or so, before, now takes me about 20 minutes. (between the different sheets, there are about between 75 to 100 changes in formulas per new employee - so the "find and replace" in formula only, was extremely useful).

  • How to search and replace in an xml file using java

    Hi all,
    I am new to java and Xml Programming.
    I have to search and replace a value Suresh with some other name in the below xml file.
    Any help of code in java it is of great help,and its very urgent.
    I am using java swings for generating two text boxes and a button but i am not able to search in the xml file thru the values that are entered into these text boxes.
    Thanks in advance.
    **XML File*
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <student>
    <stud_name>Suresh</stud_name>
    <stud_age>40</stud_age>
    </student>Also i am using SAX Parser in the java program
    any help of code or any tutorials for sax parisng is very urgent please help me to resolve this problem
    Edited by: Karthik84 on Aug 19, 2008 1:45 AM
    Edited by: Karthik84 on Aug 19, 2008 3:15 AM

    Using XPath to locate the elements you are after is very easy.
    Try something like this:
    import java.io.File;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    public class BasicXMLReplaceWithDOM4J {
         static String inputFile = "C:/student.xml";
         static String outputFile = "C:/studentRenamed.xml";
         public static void main(String[] args) throws Exception {
              // Read xml and build a DOM document
              Document doc = DocumentBuilderFactory.newInstance()
                        .newDocumentBuilder().parse(new InputSource(inputFile));
              // Use XPath to find all nodes where student is named 'Suresh'
              XPath xpath = XPathFactory.newInstance().newXPath();
              NodeList nodes = (NodeList)xpath
                   .evaluate("//stud_name[text()='Suresh']", doc, XPathConstants.NODESET);
              // Rename these nodes
              for (int idx = 0; idx < nodes.getLength(); idx++) {
                   nodes.item(idx).setTextContent("Suresh-Renamed");
              // Write the DOM document to the file
              Transformer xformer = TransformerFactory.newInstance().newTransformer();
              xformer.transform(new DOMSource(doc), new StreamResult(new File(outputFile)));
    }- Roy

  • Indesign script to find and replace from external excel file

    I have been asked to update an existing price list (set up as lots of small tables) in Indesign (500+  pages). I have been given a new Excel spreadsheet with the product codes and new prices. I am looking for some assistance on finding or creating a script that can do such a thing if at all possible to speed up the process over just copying and pasting. Does anyone have any suggestions or point me in the right direction?

    1. Your Excel conversion to FindChangeList format idea seems okay, apart from one thing: both findWhat and changeTo strings should have double quotes around them. As they are now,
    grep {findWhat:lang1"} {changeTo:"lang2} {incl...(etc.)
    the opening one after findWhat and the closing one after changeTo are missing.
    2. Your first line contains 2 definitions. Each separate definition should be on a line of its own. (This might occur elsewhere as well, didn't check.)
    3. Any double quotes inside strings will cause problems. Precede them with a backslash to 'escape' them and convert them to a literal character. I found this one:
    "(for IC5/8"V)"
    -- change to
    "(for IC5/8\"V)"
    4. Some of your strings start with double double quotes:
    changeTo:""(MITM刀具见254页 ...
    5. To prevent your problem with this order
    grep {findWhat:Inserts"} ...
    grep {findWhat:Inserts Ordering Code System"} ...
    sort your Excel list alphabetically, case preserving, in reverse order.
    You probably also want wholeWord:true, and caseSensitive:true.
    Hope this helps!

  • Find and Replace text in several files

    Can automator do that?
    I made a website in iweb and as the ones of you that had already tried it must know, it is impossible to change the font format on the links, you have to hack the code manually, changing the .css files.
    I think a trick would be to get automator to replace the code automatically, to lock for a string of text inside a group of files and save it. I just don't know how to do it. Can anybody help?
    The most I have been able to do is to get automator to open all .css files within a folder, inlcuidng all subfolders and open them on textedit.

    I doubt anyone is going to download and look at your code. Please remember that anyone who helps you here is a volunteer, and so the onus is on you to make helping you as easy as possible to do. That means you must take the effort to pare your code down to the bare minimum that shows your problem and compiles, and then post this code here. If you do decide to do this, please use code tags by highlighting your code after pasting it, and then pressing the Code button just above the editor window.
    Good luck.

  • Find and Replace String in a Column

    Hi,
    In the table data got stored with " " (Double Quotes) I need to remove these double quotes Please suggest me how to remove
    Select address from TECH_SOURCING_EMPLOYEE_DETAILS
    "No 12/32" ---> data been saved in this format in the table. I need to remove the double quotes
    Thanks
    Sudhir

    Hi,
    Use UPDATE to change existing rows in a table
    Use REPLACE to remove a given sub-qtring from a string.
    UPDATE     tech_sourcing_employee_details
    SET     address     = REPLACE (address, '"')
    WHERE     INSTR (address, '"')         > 0          -- Maybe
    ;This will remove all double-quotes from address.
    If you want to remove double-quotes only from the very beginning and end of the string, then use TRIM instead of REPLACE:
    UPDATE     tech_sourcing_employee_details
    SET     address     = TRIM ('"' FROM address)
    WHERE     INSTR (address, '"')         > 0          -- Maybe
    ;The WHERE clause is only for efficiency.
    If, whenever the column contains double-quotes, one of the double-quote is always the first character in the string, then you can change the WHERE clause to:
    WHERE     address  LIKE '"%'
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Find and Replace across multiple PDF files

    Hello,
    The company I work for has recently changed it's name from (for example!) "Rob's Company" to "Dave's Company".
    I have a folder with several thousand PDF files where "Rob's Company" is mentioned and I want to find/replace this for "Dave's Company" in one job (as opposed to opening each file and doing a find/replace in each one).
    I am happy to purchase a copy of Adobe Acrobat in order to do this, but I'm unsure if it is capable of doing so. I know it is possible to do this for individual files, but not sure that it can do a find/replace for all files in a particular folder.
    I hope someone is able to assist me, I'd be very grateful.
    Best wishes,
    Rob

    I totally agree with you regarding keeping the source files; it's common sense isn't it! I've only worked at this company for 14 days and the vast majority of docs are years old so it would be nearly impossible to trace back the owner of the document internally and then for who their contact is at the client who originally sent it over. With staff turnover you'd probably get nowhere pretty slowly!
    Thanks very much for your redact suggestion. Is that basically where you "stick" new text over the old? The phrases to be changed are reasonably simalar in length (new text is 1 character smaller) so if there was a small gap at the end of the phrase I wouldn't loose sleep over it.
    Thanks again for your help - as I say with just 14 days in the company it would be nice to get this job done without involving too many people so it looks good to my new bosses!
    Rob

  • Reformatting files in Dreamweaver: Batch series of .dwr files (find and replace) consecutively

    I have to do complicated reformatting of an entire site. It's been simplified to a series of find and replace tasks for each file. Each find and replace string has been saved as a .dwr file. Currently I have to load and execute each .dwr file.
    How do you batch process or automate this task in Dreamweaver? In other words, queue up a series of .dwr files to be executed consecutively?

    OK here we go.
    This example, a simple Dreamweaver  Command Extension, will execute two Find and Replace commands in one go. (It can be any number of Find and Replace commands.)
    The first command replaces "the" and "this" with "phe" and "phis". The second command replaces <ul> ... </ul> with <ol> ... </ol>. (These of course can be any Find and Replace.)
    You need two files: a HTML file (for the  UI) and a Javascript file (for actions). I named them "Find and Replace Test.html" and "Find and Replace Test.js". (They can be any name.)
    Find and Replace Test.html
    <!DOCTYPE HTML SYSTEM "-//Adobe//DWExtension layout-engine 10.0//dialog">
    <HTML>
    <HEAD>
    <Title>Find and Replace Test</Title>
    <script src="Find and Replace Test.js"></script>
    </HEAD>
    <BODY>
    <form>
         <p>Are you sure?</p>
    </form>
    </BODY>
    </HTML>
    Find and Replace Test.js
    function canAcceptCommand() {
        return true;
    function commandButtons() {
        return new Array("Go!", "doIt()", "Cancel", "window.close()");
    function doIt() {
        dreamweaver.setUpFindReplace({
            searchString: "th(e|is)",
            replaceString: "ph$1",
            searchWhat: "document",
            searchSource: true,
            useRegularExpressions: true
        dreamweaver.replaceAll();
        dreamweaver.setUpFindReplace({
            searchString: "<(/?)ul>",
            replaceString: "<$1ol>",
            searchWhat: "document",
            searchSource: true,
            useRegularExpressions: true
        dreamweaver.replaceAll();
        window.close();
    Basically you can call any number of this pair of functions in the script:
    dreamweaver.setUpFindReplace(findAndReplaceObject);
    dreamweaver.replaceAll();
    Place these HTML and JS files in this directory:
    Dreamweaver App Directory/Configuration/Commands/ 
    Then in Dreamweaver, open "Insert" window. (You need to have a HTML file open in order to make the Insert window active.) At the top of the Insert window there's a category dropdown menu  ("Common" etc.). Do alt + click (ctrl + click) - then you'll see an item "Reload Extenesions" at the bottom of the dropdown. This will load this extension to DW. (Alternatively you can restart DW to load the extension.)
    Now it's ready to run the Extension. Open a HTML document you want to modify. Go to "Commands" on the menu bar. At the bottom of the dropdown there should be an item "Find and Replace Test". Select and enjoy
    Notes
    This example is set to perform the Find and Replace on the current document. You can change the scope to the entire site, or the selected files, etc, just like in the Find and Replace dialogue box. The API doc is here: http://help.adobe.com/en_US/dreamweaver/cs/apiref/WS5b3ccc516d4fbf351e63e3d117f9e09bcf-7ed a.html
    You can use dreamweaver.setUpComplexFindReplace(xmlQueryString) command instead. xmlQueryString is basically <dwquery> ... </dwquery> in your .dwr files, you can copy from your .dwr files. However xmlQueryString needs to be one continuous string (no line breaks), which can be a pain The doc: http://help.adobe.com/en_US/dreamweaver/cs/apiref/WS5b3ccc516d4fbf351e63e3d117f9e09bcf-7ed 9.html
    Command Extension general example in the doc: http://help.adobe.com/en_US/dreamweaver/cs/extend/WS5b3ccc516d4fbf351e63e3d117f53d6ec3-7fe 6.html
    I hope all of these make sense...
    Kenneth Kawamoto
    http://www.materiaprima.co.uk/

  • Find and replace in files does not refresh when changes are made

    Using RH10, I search for a term with the Find and Replace Options pod. I use the Find Results list as a reference only, and open each file from the Topic List. I do this instead of opening the topics from the Find Results tab because I want to see the WYSIWYG changes. Anyway, I make my edits and delete the search term from each topic. Then, to make sure I have done all the work, I run the search again. I expect to see no or at least fewer matches than before, but I still get some or all of the same results as before, even though I double-check the Design and HTML views of the topics and even check the source of a topic separately in Notepad, all indicating that the search term is gone from the topic.
    There is some ridiculous lingering or echo going on. I make sure to select Look in: <Current Project>, and the paths of all the Find Results files are fine. How do you refresh the search so that this echo doesn't occur?
    Also, I close the Find and Replace Options pod, reopen it and start the search again, and the same results are there.
    Message was edited by: DMilkes

    Hi there
    To avoid the message about the file being modified, close all topics in the editor before commencing with any find and replace operations. The message is produced because you have the aforementioned topics open in the editor.
    As you mention "Find and replace in files", I'm guessing you are referring to version 8. I just opened version 8 and performed a find and replace to confirm. There is a button allowing you to clear all.
    On the clicking and dragging to create a link, it's never worked that way. You simply cannot drag from the Topic List pod to do it. But you can from the Project Manager pod. Perhaps you should consider submitting a Wish Form to ask for the ability to click and drag from the Topic List pod to create links.
    As far as rearranging your topics into different folders, as long as you do it from inside RoboHelp you shouldn't be destroying any links. RoboHelp will update references for you as you move things around. The only issue is if you are automatically creating your TOC structure based on the project structure. But usually that's a one time shot. From there forward you just manage things using the TOC editor.
    Hopefully this helps... Rick
    Helpful and Handy Links
    RoboHelp Wish Form/Bug Reporting Form
    Begin learning RoboHelp HTML 7 or 8 within the day - $24.95!
    Adobe Certified RoboHelp HTML Training
    SorcerStone Blog
    RoboHelp eBooks

  • Can I do a find and replace on .cfm files only and not search .html or .txt?

    Hi.  I'm using Dreamweaver CS4.  I would like to do a find and replace through my site with Dreamweaver but I only want it to search through .cfm files.  Currently it is searching through .html and .txt files along with .cfm.  Is there a way to do a find and replace on just .cfm files?
    - Tom

    You can't do it on just one type of file. However, you can do find and replace in selected files. Ctrl-click to select the targeted files in the Files panel, and then choose Selected Files in Site from the Find In drop-down.

  • VBA Word Find and Replace characters but excluding certain characters

    I am trying to write VBA code in Word that I will eventually run from a VBA Excel module. The aim of the project is to find specific strings in the open Word document that have length of either one or two characters and are of a certain format, and replace
    them with other strings in the same format. This is to do with transposing (i.e. changing the musical key) of chord symbols in a songsheet in Word. The Find and Replace strings are contained in ranges in an Excel workbook, which is why I want to eventually
    run the code from Excel. I'm much more experienced in writing VBA code in Excel than in Word, and I'm fairly confident with transferring the 'Word VBA' code into an Excel module.
    At the moment I'm trying out code entirely in Word, and I've come across a stumbling block. For example, I want it to Find "A" and replace with "B",
    BUT only if the "A" is NOT followed by "#" (sharp) or "b" (flat).
    Here is the code I've got in Word VBA, which I obtained by editing code produced by the recorder:
    Sub F_R()
    'Find text must have specific font
    With Selection.Find.Font
    .Bold = True
    .Underline = wdUnderlineWords
    .Superscript = False
    .Subscript = False
    End With
    'Replacement text must have specific font
    With Selection.Find.Replacement.Font
    .Bold = True
    .Underline = wdUnderlineWords
    .Superscript = False
    .Subscript = False
    End With
    'Find & Replace strings
    With Selection.Find
    .Text = "A" 'hard-coded here for testing, but this will
    'eventually be referenced to a cell in Excel
    .Replacement.Text = "B" 'hard-coded here for testing, but this will
    'eventually be referenced to a cell in Excel
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = True
    .MatchWholeWord = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    End Sub
    For the Find & Replace section I want to do something like:
    With Selection.Find
    .Text = "A"
    .Text <> "A#"
    .Text <> "Ab"
    .Replacement.Text = "B"
    End With
    - but this produces a syntax error, presumably because you can have only one .Text line (or it won't accept <>?)
    I tried adopting the way of excluding chars when using the Like operator, and while it compiles, it will not replace
    any "A":
    With Selection.Find
    .Text = "A[!b#]"
    .Replacement.Text = "B"
    End With
    I suspect that I'm going to have to change tack completely in the way I'm doing this. Do you have any suggestions, please?
    The chord names/symbols are preceded/succeeded by either spaces or paragraph returns and can look like these, for example (all Font Bold and Underlined words only):
    C<sup>7</sup>
    Dm<sup>7</sup>
    Eb<sup>-5</sup>
    Bb<sup>+11</sup>
    F#m<sup>7</sup>
    i.e. [ABCDEFG][b # | optional][m |optional][- + | superscript, optional][2 3
    5 6 7 9 11 13 | superscript, optional]
    The crux of my problem is that the note A should be treated as entirely distinct from Ab or A# (and similar for other flattened/sharpened notes).
    Sorry for long post.

    Hi Ian,
    It is not easy to find Microsoft forums. However this forum is for the Visual Studio Net version. 
    Try this forum for VBA.
    https://social.msdn.microsoft.com/Forums/en-US/home?forum=isvvba
    Success
    Cor

  • Multi find and replace

    When using Multi find and replace the system does not replace
    all files. Any suggestions?

    Hi 1motivate and welcome to the RH community.
    The in built find and replace tool (if that is what you are
    using) has some limitations and is known to have issues. Most of us
    use a third party tool. FAR and BkReplacem being two of them. My
    own personal favourite is
    FAR as it does a lot more
    than find and replace (even author help files!) and is relatively
    cheap. Others swear by BkReplacem and this is freeware.

Maybe you are looking for

  • Transferring DAQ acquisition data via TCP/IP

    Hi all. I am trying to write a program which shares the raw data acquired from a DAQ acquisition device to several computers at the same time. I am using a NI-USB DAQ 6251 to acquire 2 channels of data at 200kS/s on each channel. I need to send this

  • I tunes is skipping

    I read several posts about this, but nothing seems to be helping the issue. My i tunes is skipping on every song. Is there a way to fix this problem?

  • Parsing Query string using Client Object model [ECMA]

    hello i want to access querystring using client object model using ECMA script. for eg http://localhost:80/demopage.aspx?test=123 can we read value of test using ECMA script regards Manish

  • Classes and JSPs in Tomcat-4.1.24

    Where to put the class files and how to call them in the jsps in Tomcat-4.1.24. <br>In Tomcat-3.2.4 I used to put them in WEB-INF/classes and call them. The same jsp's working in Tomcat-3.x are not working in 4.1.24 version. Any idea??? Thanx in adva

  • Internal table oerations using for all entries

    Hi folks I want to display an output of SO number, SO Date( from VBAK) , SO Item, SO item category (from VBAP) , MAterial no., MAt type (from MARA) Using 3 internal tables for each table fields and applying FOR ALL ENTRIES and populating a final outp