Hyperlinks don't copy from Excel to Excel when using Data Connection - excel

I'm an end user who hosts a public Excel 2010 Workbook (without macros, so other users can feel safe) which contains all of the individual player stats for the Madden NFL Mobile game by EA Sports.
I've also created a non-public Macro-Enabled 2010 Workbook which I use to automate the extraction all of the relevant data from a 3rd party website and reparse all of that data into a spreadsheet layout I desire.
My first column of the Macro-Enabled Workbook contains the player's name with a hyperlink to that player's webpage on that 3rd party website, and the macro creates that hyperlink for me just fine.
When I use a Data Connection to automate the syncing of the data from the Macro Book to the Non-Macro Book, everything copies fine, except for the player's name which is only in plain text (no hyperlink).
I also tried to make that first column an excel hyperlink formula (instead of VBA's hyperlink function), but the formula won't transfer via the data connection either.
Is there something I can edit maybe inside of the Data Connection file (.odc) to accomplish my goal?
My only other workaround so far is to add 2 extra hidden columns containing the text link and player name, and then mucking around with the destination Table to make the first column a pre-defined excel HYPERLINK formula to convert the two columns back into a hyperlink.
Any ideas?

Nevermind, I decided to just use a powershell script and batch file to do all of my copy/pasting, and skipping the whole Data Connection thing all together.
My "TransferMaddenData.ps1" PowerShell Code:
$path = "C:\Users\Grego\Desktop\MaddenData.xlsm"
$Excel = New-Object -ComObject excel.application
$Excel.visible = $false
$Workbook = $Excel.Workbooks.open($path)
$Worksheet = $Workbook.WorkSheets.item("DataOutput")
$Rows = $Worksheet.UsedRange.Rows.Count
$Rows += 1
$Cells = "A3:BD" + $Rows
$Worksheet.activate()
$range = $WorkSheet.Range($Cells)
$range.Copy() | out-null
$path = "C:\Users\Grego\Desktop\Madden1.xlsm"
$Workbook2 = $Excel.Workbooks.open($path)
$Worksheet = $Workbook2.Worksheets.item("Raw Data")
$range = $Worksheet.Range("A3")
$Worksheet.Paste($range)
$Workbook2.Save()
$Workbook.Close()
$Excel.Quit()
Remove-Variable -Name excel
[gc]::collect()
[gc]::WaitForPendingFinalizers()
This is my "FixMadden.bat" batch file:
#echo off
color 1F
echo.
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "C:\Users\Grego\Desktop\TransferMaddenData.ps1"
:EOF
echo Waiting seconds
timeout /t 10 /nobreak > NUL
Hope this maybe helps someone else someday!

Related

Powershell export csv results to multiple sheets in an excel workbook

I run a lot of scans against our AD looking for deficiencies (i.e. users without an email, user ID blank, on-leave but AD account not disabled, etc) and all my results are exported to csv files. I'd like each csv result stored on a sheet in a single excel workbook. I've found a lot of sites showing how to convert a csv to an xls or how to export to a single xls sheet but I can't find anything else meeting my needs. I don't have the ability to import the Import-Excel / Export-Excel modules from the PS gallery. Any suggestions on how I can export 3 CSV files (actually array objects - not sure they need to be exported to CSV first) to three sheets in a workbook?
What I've found so far:
# Create Excel object
$excel = new-object -comobject Excel.Application
# Create a new workbook
$workbook = $excel.workbooks.add()
# Name a worksheet
$workbook.WorkSheets.Item(1).Name = "Users"
# Add data from a csv to the current sheet
$workbook = $excel.workbooks.add(“C:\export_users.csv”)
What I can't figure out is how to add data from additional csv files onto additional sheets in the workbook.
Add another worksheet with another Add().
$excel = New-Object -ComObject Excel.Application
$wb1 = $excel.workbooks.add()
$wb1.WorkSheets.Item(1).Name = 'Users 1'
$wb1.Worksheets.Item(1).Name
$wb1.Worksheets.Count
$wb1.Worksheets.Add() | Out-Null
$wb1.WorkSheets.Item(2).Name = 'Users 2'
$wb1.Worksheets.Item(2).Name
$wb1.Worksheets.Count
I have had some success using the ImportExcel module for PowerShell.

How to use PowerShell to write a files content to different rows in Excel

I am trying to automate the following manual task, and am struggling with part of it:
1) Open a text file that contains multiple lines containing data.
2) Copy the contents of this file to the clipboard.
3) Open and Excel spreadsheet.
4) Rename the spreadsheet to Test.
5) Paste the contents of the clipboard.
When this is done manually the content is pasted and each line in the text file is inserted as a new row in column A.
Originally the customer wanted all of the file content to be injected into cell A1. I was able to achieve this with the below PowerShell code.
However they have since changed this back to wanting each line of text to go into a separate row in column A.
I cannot figure out how to do this gracefully via the Get-Content method of copying out the text data. I have seen workarounds to this issue whereby Excel opens the text file and copies the text into an intermediate workbook and then into the final workbook.
Could someone please let me know if it's possible to amend my already working code below so that it adds the text to rows in column A rather than to cell A1?
# Clear the screen of any previous text.
cls
$ExcelFile="C:\Users\User\Desktop\Test\Test.xlsx"
$TextFile="C:\Users\User\Desktop\Test\TestText.txt"
$Content = Get-Content $TextFile -Raw
# Perform operations in Excel based on content of the downloaded file.
$Excel = New-Object -ComObject Excel.Application
# For troubleshooting enable the below to view Excel as file is manipulated:
#$Excel.Visible=$true
# Disable Excel alerts. Hash this line out for troubleshooting.
$Excel.DisplayAlerts = $false
# Set up workbook...
$Workbook = $Excel.Workbooks.Add()
$Data = $Workbook.Worksheets.Item(1)
$Data.Name = 'Test'
# Insert Data
$Data.Cells.Item(1,1) = "$Content"
# Format, save and quit excel
$UsedRange = $Data.UsedRange
$UsedRange.EntireColumn.AutoFit() | Out-Null
$Workbook.SaveAs("$ExcelFile")
$Excel.Quit()
I know that the part I would need to change is as follows, but I'm not sure what to change it to:
# Insert Data
$Data.Cells.Item(1,1) = "$Content"
Many thanks in advance.
To do this, you need to find the last used row in the sheet and write each line from there:
$ExcelFile = "C:\Users\User\Desktop\Test\Test.xlsx"
$TextFile = "C:\Users\User\Desktop\Test\TestText.txt"
# Perform operations in Excel based on content of the downloaded file.
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $false
$Excel.DisplayAlerts = $false
# open the file and select the first worksheet
$WorkBook = $Excel.Workbooks.Open($ExcelFile)
$WorkSheet = $Workbook.Worksheets.Item(1)
# get the first unused row
$row = ($WorkSheet.UsedRange.Rows).Count + 1
# fill in the data
Get-Content -Path $TextFile | ForEach-Object {
$WorkSheet.Cells.Item($row++, 1) = $_
}
# format column A and save the file
$UsedRange = $WorkSheet.UsedRange
$UsedRange.EntireColumn.AutoFit() | Out-Null
$WorkBook.Save()
# quit excel and clean up the used COM objects
$Excel.Quit()
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($WorkSheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($WorkBook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
I think the solution would be to read each line in content by for or foreach loop
in loop, write the line's content into the last row of column A in the excel file.
It's will be something like this
foreach($line in $Content){
$Data.Cells.Item($LastRow,1) = $line
}

Paste\Return into Cell A1 of open Excel sheet

I wish to take a string generated in PowerShell and paste\return that string into Cell A:1 of an OPEN spreadsheet. I have researched this but I dont understand the excel specific syntax.
Do I need to identify and declare the PID for the specific Excel workbook thats running and if so how?
I know how to create a new workbook and add the text to cell A:1 but not one which is already open. It must also "press return" to execute the spreadsheet functions once pasted.
I dont know where to start other than: ((new-object -com "excel.application").Workbooks.Add()).application.Visible=$True
I have scoured the web but have not found any examples that make sense. Please help
You can achieve it by using the below script
#Specify the path of the excel file
$FilePath = "path\test.xlsx"
#Specify the Sheet name
$SheetName = "Sheet1"
# Create an Object Excel.Application using Com interface
$objExcel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application')
# Disable the 'visible' property so the document won't open in excel
$objExcel.Visible = $false
# Open the Excel file and save it in $WorkBook
$WorkBook = $objExcel.Workbooks.Open($FilePath)
# Load the WorkSheet 'BuildSpecs'
$WorkSheet = $WorkBook.sheets.item($SheetName)
$WorkSheet.Cells.Item(1,1) = "Link" #Updates the first cell (A1)
$WorkBook.Save()
$WorkBook.Close()
Make sure the file has write permissions from PowerShell scripts.
If you want to edit the sheet which is already open, change the path of the file and mention the sheet name properly and it would work as expected.

Force open CSV with Column Data Format = TEXT in Excel (Powershell)

I have this CSV file I generate using Export-CSV. Everything is fine with it but it display like this when opening in Excel because the cells are not formatted as TEXT:
I want to force open the CSV with the cells all set to TEXT like you can do manually with the interface.
Is there a way to automate that with PowerShell, opening the CSV in Excel with cells formatted as text?
There is a little trick you can use - convert your data to html, and save with "xls" extention. For example:
Get-Process | convertto-html | Out-File csv2.xls
You'll see a warning when opening it, just click OK.
You can suppress that warning message by adding extra key in registry:
open regedit
HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Excel\Security
Create a new DWORD with name ExtensionHardening and value 0
Found a very good way to make it happen!
After generating your CSV file, here is how to automatically load it into Excel with AutoFit column width and TEXT format for cells :) :
$Fichier = "PATH_TO_CSV.csv"
$objExcel = New-Object -ComObject Excel.Application
$WorkBook = $objExcel.Workbooks.Open($Fichier)
$WorkSheet = $WorkBook.worksheets.item(1)
$objExcel.Visible = $true
$Range = $worksheet.UsedRange.Cells
$range.NumberFormat = "#"
$WorkSheet.Columns("A:B").AutoFit()

Excel com-object via powershell

I am doing data output to csv file via powershell. Generally things goes well.
I have exported the data to csv file. It contains about 10 columns. When I open it with MS Excel it's all contained in first column. I want to split it by several columns programmatically via powershell(same GUI version offers). I could make looping and stuff to split the every row and then put values to appropriate cell but then it would take way too much time.
I believe there should be an elegant solution to make one column split to multiple. Is there a way to make it in one simple step without looping?
This is what I came up with so far:
PS, The CSV file is 100% FINE. The delimiter is ','
Get-Service | Export-Csv -NoTypeInformation c:\1.csv -Encoding UTF8
$xl = New-Object -comobject Excel.Application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open('c:\1.csv')
$ws = $wb.Sheets|?{$_.name -eq '1'}
$ws.Activate()
$col = $ws.Cells.Item(1,1).EntireColumn
This will get you the desired functionality; add to your code. Check out the MSDN page for more information on TextToColumns.
# Select column
$columnA = $ws.Range("A1").EntireColumn
# Enumerations
$xlDelimited = 1
$xlTextQualifier = 1
# Convert Text To Columns
$columnA.texttocolumns($ws.Range("A1"),$xlDelimited,$xlTextQualifier,$true,$false,$false,$true,$false)
$ws.columns.autofit()
I had to create a CSV which had "","" as delimiter to test this out. The file with "," was fine in excel.
# Opens with all fields in column A, used to test TextToColumns works
"Name,""field1"",""field2"",""field3"""
"Test,""field1"",""field.2[]"",""field3"""
# Opens fine in Excel
Name,"field1","field2","field3"
Test,"field1","field.2[]","field3"
Disclaimer: Tested with $ws = $wb.Worksheets.item(1)

Resources