vba字:如果然后找到并替换

时间:2017-10-12 17:13:46

标签: if-statement ms-word find word-vba replacewith

在此代码中,我想执行以下操作:

  • 如果单词以字母M替换,则替换为字母N。
  • 如果单词以字母N结尾,请用字母M替换。
  • 我不太清楚使用IF - Then语句。 任何帮助将不胜感激。

    Sub find_end()   
        Selection.Find.ClearFormatting
        Selection.Find.Replacement.ClearFormatting
        With Selection.Find
            .Text = "[nm]>"
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
            .MatchWildcards = True
            Selection.Find.Execute
            With Selection
            If Selection.Find.Found = n Then
                Selection.TypeText Text:=m
            ElseIf Selection.Find.Found = m Then
                Selection.TypeText Text:=n
            End If
    End Sub
    

1 个答案:

答案 0 :(得分:0)

我修改了代码:Repeating Microsoft Word VBA until no search results found 它将通过文件旋转并替换每个单词的最后一个字母(如果它是'或' n')。请注意,如果您可能找到超过2000米或更长时间的代码,则可能需要删除该代码中的循环检查。

package com;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.util.NumberToTextConverter;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class XlsxReader
{             
                private XSSFWorkbook workbook;
                private XSSFSheet Sheet;
                private XSSFRow row;
                private XSSFCell cell;
                private FileInputStream fis;
                private int iIndex;
                private static String sFileName1 = null;
                public XlsxReader(String sFileName)
                {
                                sFileName1 = sFileName;
                                try
                                {
                                                //app = new ConfigManager("App");
                                                String dir = null;
                                                File directory = new File (".");
                                                dir = directory.getCanonicalPath();
                                                String sFilePath = dir + "\\Data\\" + sFileName + ".xlsx";
                                                //String sFilePath = "D:\\FrameWorks\\SeleniumJava\\WorkSpace\\GuidewirePC\\Data\\Data.xlsx";
                                                File file = new File(sFilePath);
                                                if(file.exists())
                                                {
                                                fis = new FileInputStream(sFilePath);
                                                workbook = new XSSFWorkbook(fis);

                                                fis.close();
                                                }
                                                else
                                                {
                                                                //UtilityMethods.infoBox("File with name-'"+sFileName+"' doesn't exists in Data Folder, Please Re-check given file name", "Config.properties");
                                                                System.out.println("doesn't exists in Data Folder" );
                                                                System.exit(0);
                                                }
                                }
                                catch (Exception e)
                                {                                             
                                                System.out.println("Exceptione is ="+e.getMessage());
                                                //UtilityMethods.infoBox(e.getMessage(), "Exception");
                                                System.exit(0);
                                }
                }

                public void setCellData(String sheetName,String Result,  int RowNum, int ColNum) throws Exception      {

                                iIndex = workbook.getSheetIndex(sheetName);
                                if(iIndex==-1)
                                {
                                                //UtilityMethods.infoBox("Sheet with name-'"+sheetName+"' doesn't exists in this excel file, please Re-check given sheet name","Missing sheet");
                                                System.exit(0);
                                }
                                                Sheet = workbook.getSheetAt(iIndex);
                                                row = Sheet.getRow(RowNum);
                                                Cell cell2 = row.createCell(ColNum);
                                                cell2.setCellValue(Result);

                                                //cell = Sheet.getRow(RowNum).getCell(ColNum); 
            //cell.setCellValue(Result);
                                                String dir = null;
                                                File directory = new File (".");
                                                dir = directory.getCanonicalPath();
                                                String sFilePath = dir + "\\Data\\" + sFileName1 + ".xlsx";
                                                FileOutputStream webdata=new FileOutputStream(sFilePath);
                                                workbook.write(webdata);
                                }

                public int getRowCount(String sheetName) throws Exception
                {
                                int number = 0;
                                if(isSheetExist(sheetName))
                                {
                                                Sheet = workbook.getSheetAt(iIndex);
                                                number=Sheet.getLastRowNum()+1;
                                }
                                return number;

                }             

                /**
                * Purpose- To get column count of specified sheet
                * @param sheetName- Sheet name should be provided
                * @return- Returns value of column count
                * @throws Exception
                */
                public int getColumnCount(String sheetName) throws Exception
                {                             
                                if(isSheetExist(sheetName))
                                {
                                                Sheet = workbook.getSheet(sheetName);
                                                row = Sheet.getRow(0);

                                                if(row==null)
                                                                return -1;

                                                return row.getLastCellNum();
                                }
                                return 0;                             
                }
                public String getCellData(String sheetName,String colName,int rowNum,int rowPadding,int columnPadding){
                                try{

                                                if(isSheetExist(sheetName))
                                                {                                             
                                                                if(rowNum <=0)
                                                                {
                                                                                //UtilityMethods.infoBox("Row number should be greater than 0", "");
                                                                                System.exit(0);
                                                                                return "";
                                                                }
                                                                int col_Num=-1;                              
                                                                Sheet = workbook.getSheetAt(iIndex);

                                                                                row=Sheet.getRow(rowPadding);

                                                                for(int i=columnPadding;i<row.getLastCellNum();i++)
                                                                                {             
                                                                                if(row.getCell(i).getStringCellValue().trim().contains(colName.trim()))
                                                                                                {
                                                                                                                col_Num=i;

                                                                                                                break;
                                                                                                }

                                                                                }

                                                                if(col_Num==-1)
                                                                                {
                                                                                                //UtilityMethods.infoBox("Column with specified name"+colName+" is not being displayed", "Config.properties");
                                                                                                System.exit(0);
                                                                                                return "";
                                                                                }

                                                                row = Sheet.getRow(rowNum-1);
                                                                if(row==null)
                                                                                return "";
                                                                cell = row.getCell(col_Num);

                                                                if(cell==null)
                                                                                return "";                                            
                                                                if(cell.getCellType()==Cell.CELL_TYPE_STRING)
                                                                  return cell.getStringCellValue();
                                                                else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA )
                                                                {

                                                                                String cellText=NumberToTextConverter.toText(cell.getNumericCellValue());

                                                                                  if (HSSFDateUtil.isCellDateFormatted(cell))
                                                                                  {
                                                                           // format in form of D/M/YY
                                                                                                  double d = cell.getNumericCellValue();
                                                                                                  Calendar cal =Calendar.getInstance();
                                                                                                  cal.setTime(HSSFDateUtil.getJavaDate(d));                                                                        
                                                                                                  int Year = cal.get(Calendar.YEAR);
                                                                                                  int Day = cal.get(Calendar.DAY_OF_MONTH);
                                                                                                  int Month = cal.get(Calendar.MONTH)+1;
                                                                          cellText = Day + "/" + Month + "/" + (String.valueOf(Year)).substring(2);
                                                                      }                                         
                                                                                  return cellText;
                                                                  }
                                                                else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
                                                      return "";
                                                                else
                                                                  return String.valueOf(cell.getBooleanCellValue());
                                                }
                                                return "";
                                }
                                catch(Exception e)
                                {                                             
                                                System.out.println("Exceptione is =" + e.getMessage());
                                                //UtilityMethods.infoBox("row "+rowNum+" or column "+colName +" does not exist in xls", "Config.properties");
                                                return "row "+rowNum+" or column "+colName +" does not exist in xls";
                                }
                }
                public String getCellData(String sheetName,int colNum,int rowNum){
                                try{

                                                if(isSheetExist(sheetName))
                                                {                                             
                                                                if(rowNum <=0)
                                                                {
                                                                                //UtilityMethods.infoBox("Row number should be greater than 0", "");
                                                                                System.exit(0);
                                                                                return "";
                                                                }

                                                                Sheet = workbook.getSheetAt(iIndex);
                                                                row = Sheet.getRow(rowNum-1);
                                                                if(row==null)
                                                                                return "";
                                                                cell = row.getCell(colNum);

                                                                if(cell==null)
                                                                                return "";                                            
                                                                if(cell.getCellType()==Cell.CELL_TYPE_STRING)
                                                                  return cell.getStringCellValue();
                                                                else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA )
                                                                {
                                                                                // String cellText  = String.valueOf(cell.getNumericCellValue());
                                                                                String cellText=NumberToTextConverter.toText(cell.getNumericCellValue());
                                                                                  if (HSSFDateUtil.isCellDateFormatted(cell))
                                                                                  {
                                                                           // format in form of D/M/YY
                                                                                                  double d = cell.getNumericCellValue();
                                                                                                  Calendar cal =Calendar.getInstance();
                                                                                                  cal.setTime(HSSFDateUtil.getJavaDate(d));                                                                        
                                                                                                  int Year = cal.get(Calendar.YEAR);
                                                                                                  int Day = cal.get(Calendar.DAY_OF_MONTH);
                                                                                                  int Month = cal.get(Calendar.MONTH)+1;
                                                                          cellText = Day + "/" + Month + "/" + (String.valueOf(Year)).substring(2);
                                                                      }                                         
                                                                                  return cellText;
                                                                  }
                                                                else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
                                                      return "";
                                                                else
                                                                  return String.valueOf(cell.getBooleanCellValue());
                                                }
                                                return "";
                                }
                                catch(Exception e)
                                {                                             
                                                System.out.println("Exceptione is =" + e.getMessage());
                                                //UtilityMethods.infoBox("row "+rowNum+" or column "+colNum +" does not exist in xls", "Config.properties");
                                                return "row "+rowNum+" or column "+colNum +" does not exist in xls";
                                }
                }



}