Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

I have two different Excel files.I am trying to create powershell script to find data from column 2 (first file) and replace data into column 1(first file) also need to modify second excel files.

$
0
0
function excel_search_replace ( $worksheet, $column_name, $search_str, $replace_str ){

echo "Replacing all '$search_str' with '$replace_str' in column '$Name'"

$range = $worksheet.Range( "$($column_name)1" ).EntireColumn

#$range = $worksheet.Range( "$($column_name)1","$($column_name)2" ).EntireColumn

#$Range = $Worksheet.Range("A1","B1").EntireColumn

$search = $range.find( $search_str )

$i = 0

if ( $search -ne $null ) {   

   $i += 1

       $first_addr = $search.Address

       do {

           $i += 1

         $search.value() = $replace_str

         $search = $range.FindNext( $search )

   } while ( $search -ne $null -and $search.Address -ne $first_addr )

    }

    echo "...Found and replaced $i instances of '$search_str'"

    return $void

}

$source_file = 'C:\test.xlsm'

$excel_obj = New-Object -ComObject 'Excel.Application'

$excel_obj.DisplayAlerts = $false

$excel_obj.Visible = $false

$workbook = $excel_obj.Workbooks.Open( $source_file ) # Open the file

#$Range = $Worksheet.Range("A1","B1").EntireColumn

$sheet = $workbook.Sheets.Item( 1 ) # select target worksheet by index

excel_search_replace $sheet 'B' '14444' '22225'

[void]$workbook.save() # Save file

[void]$workbook.close() # Close file

[void]$excel_obj.quit() # Quit Excel

[Runtime.Interopservices.Marshal]::ReleaseComObject( $excel_obj ) >$null # Release COM

Thanks to anyone who can help and for your time.

Regards,

Parth



Viewing all articles
Browse latest Browse all 21975

Trending Articles