Transposing Excel through vbscript - excel

I have an Excel spreadsheet that I have exported from some other program.
It has rows that are colored based on few business conditions.
Now I have to transpose the whole excel sheet along with the colors and formatting.
Please note that I have to do this using Vbscript only.
This is the code I've written so far, but this transposes without the formatting:
sub transpose
On Error Resume Next
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
objExcel.Workbooks.Add()
set table = ActiveDocument.GetSheetObject( "CH01" )
CellRect = ActiveDocument.GetApplication().GetEmptyRect()
CellRect.Top = 0
CellRect.Left = 0
CellRect.Width = table.GetColumnCount
CellRect.Height = table.GetRowCount
set CellMatrix = table.GetCells( CellRect )
for RowIter=CellRect.Top to CellRect.Width-1
for ColIter=CellRect.Left to CellRect.Height-1
ObjExcel.Cells(RowIter+1, ColIter+1).Value = CellMatrix(ColIter)(RowIter).Text
'msgbox(CellMatrix(ColIter)(RowIter).Text)
next
next
objExcel.ActiveWorkbook.SaveAs("C:\Documents and Settings\prasanna\Desktop\test3.xls")
objExcel.Application.Workbooks.Open("C:\Documents and Settings\prasanna\Desktop\test3.xls")
objExcel.Application.Visible = True
objExcel = Nothing
end sub

Phew.., this costed some time and experimenting, here a working solution for office 2012
const xlPasteValuesAndNumberFormats = 12 'doesn't work with Excel 2010 ?
const xlFormats =-4122
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = false
if you allready have your target xls you can skip these lines
Set wbkDest = objExcel.Workbooks.Add
wbkDest.saveAs "c:\test2.xls"
wbkDest.close
and go on here
Set objWorkbook1= objExcel.Workbooks.Open("C:\test1.xls")
Set objWorkbook2= objExcel.Workbooks.Open("C:\test2.xls")
objWorkbook1.Worksheets("Sheet1").UsedRange.Copy
'we have to do the paste twice, once for the values, once for the formats
objWorkbook2.Worksheets("Sheet1").Range("A1").PasteSpecial xlPasteValuesAndNumberFormats
objWorkbook2.Worksheets("Sheet1").Range("A1").PasteSpecial xlFormats
objWorkbook1.save
objWorkbook2.save
objWorkbook1.close
objWorkbook2.close
set objExcel=nothing

Related

How to Copy specific range column values from one excel 365 file to another using VBScript? [duplicate]

This question already has answers here:
Why does "Paste Method of Worksheet class failed" occasionally occur?
(4 answers)
Runtime error 1004 : paste method of worksheet class failed
(4 answers)
Closed 9 months ago.
start edit 20220610
I'm trying to copy specific column values (range "M:P") from one excel 365 file to the other on the range "M:P", using VBScript.
Master.xlsx file structure
Copy_2022.xlsx file structure (after the copy columns from Master.xlsx)
The copy of specific column values working correctly from Master.xlsx file to Copy_2022.xlsx file.
But the problem is that the copied columns values start from cell M1 and not from cell M4 on Copy_2022.xlsx file.
This is what I've tried.
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open("C:\Master.xlsx")
Set objWorkbook2 = objExcel.Workbooks.Open("C:\Copy_2022.xlsx")
Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Activate
objWorkbook2.Worksheets(1).UnProtect
Set objRange = objWorkSheet.Range("M:P").EntireColumn
objRange.Copy
Set objWorksheet2 = objWorkbook2.Worksheets(1)
objWorksheet.Activate
Set objRange = objWorkSheet2.Range("M:P")
objWorksheet.Paste(objRange)
objWorkbook2.Save
objWorkbook2.Close
objWorkbook.Close
objExcel.Quit
Set objExcel = Nothing
Any suggestion?
end edit 20220610
I'm trying to copy specific column values (range "M:P") from one excel 365 file to the other on the range "M:P", using VBScript.
This is what I've tried.
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open("C:\Master.xlsx")
Set objWorkbook2 = objExcel.Workbooks.Open("C:\Copy_2022.xlsx")
Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Activate
Set objRange = objWorksheet.Range("M:P").EntireColumn
objRange.Copy
Set objWorksheet2 = objWorkbook2.Worksheets(1)
objWorksheet2.Activate
objWorksheet.Range("M:P").EntireColumn.Copy objWorksheet2.Paste
objWorksheet2.Range("M:P")
objWorkbook2.Save
objWorkbook2.Close
When the code reaches the below line I am getting the below error.
objWorksheet.Range("M:P").EntireColumn.Copy objWorksheet2.Paste
Run Time Error '1004': Paste Method Of worksheet Class Failed error
Any suggestion?
Thanks in advance for any help.
Really appreciated
edit
New version same error
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open("C:\Master.xlsx")
Set objWorkbook2 = objExcel.Workbooks.Open("C:\Copy_2022.xlsx")
Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Activate
Set objRange = objWorksheet.Range("M:P").EntireColumn
objRange.Copy
Set objWorksheet2 = objWorkbook2.Worksheets(1)
objWorksheet2.Activate
objWorksheet.unprotect
objWorksheet2.unprotect
objWorksheet.Range("M:P").EntireColumn.Copy objWorksheet2.Paste
objWorksheet2.Range("M:P")
objWorksheet.protect
objWorksheet2.protect
objWorkbook2.Save
objWorkbook2.Close

Error copying cells using PasteSpecial method

Set objExcel = createObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\deven.kamlesh.jain\Desktop\abcd.xlsx")
iRow = objworkbook.sheets("Sheet1").Usedrange.rows.Count
objworkbook.Sheets("sheet1").Range("A1:C"& iRow).Copy
objExcel.visible = true
Set Obj1 = objexcel.workbooks.add()
objExcel.displayalerts = false
Obj1.saveas("Copied abcd")
Obj1.Sheets("Sheet1").Range("A1").PasteSpecial
I am trying to copy one file to another, but I get an error saying that the PasteSpecial method of the Range class failed.
The reason why PasteSpecial fails with the observed error is because the SaveAs operation clears the copied data. Move the SaveAs after the PasteSpecial and move the Copy right before the PasteSpecial. I would also recommend to put general configuration properties like Visible or DisplayAlerts right after the instantiation of the application object.
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False
Set objWorkbook = objExcel.Workbooks.Open _
("C:\Users\deven.kamlesh.jain\Desktop\abcd.xlsx")
Set Obj1 = objExcel.Workbooks.Add
iRow = objWorkbook.Sheets("Sheet1").UsedRange.Rows.Count
objWorkbook.Sheets("sheet1").Range("A1:C"& iRow).Copy
Obj1.Sheets("Sheet1").Range("A1").PasteSpecial
Obj1.SaveAs "Copied abcd"

Copy column's data from multiple excel files and paste it in new excel file

I want to copy a specific column from the excel files located in a folder and paste all the values in a new excel sheet.
Completed-
I am able to loop through all the files located in a folder.
I am able to copy the data from specific column.
Not able to complete:
Not able able to paste the copied data.
I want to copy only the distinct values.
I want to copy columns till the rows are there. like if there are 7
rows then copy 7 values of column. My copy command is copying all
the values up to last row of excel sheet.
My code (VBScipt)-
strPath="C:\Test"
Set objExcel= CreateObject("Excel.Application")
objExcel.Visible= True
Set objExcel2= CreateObject("Excel.Application")
objExcel2.Visible= True
objExcel2.Workbooks.open("C:\Test\New Folder\4.xlsx")
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder (strPath)
For Each objFile In objFolder.Files
If objFso.GetExtensionName(objFile.Path) = "xlsx" Then
objExcel.Workbooks.Open(objFile.Path)
Set Source=objExcel.Activeworkbook.Sheets(1).Columns("G")
Source.Copy
Set dest=objExcel2.Activeworkbook.Sheets(1).Columns("A")
dest.Paste
objExcel.Activeworkbook.save
objExcel.Activeworkbook.close
objExcel2.Activeworkbook.save
objExcel2.Activeworkbook.close
End If
Next
This function will return the used range for a given column on a worksheet.
Private Function getRange(ByVal ColumnName As String, ByVal Sheet As Worksheet) As Range
Set getRange = Sheet.Range(ColumnName & "1", ColumnName & Sheet.Range(ColumnName & Sheet.Columns(ColumnName).Rows.Count).End(xlUp).Row)
End Function
If you use this in-place of your Set Source=objExcel.Activeworkbook.Sheets(1).Columns("G") it should do what you want.
eg: Set Source = getRange("G", objExcel.Activeworkbook.Sheets(1))
You might need to change your dest to a cell instead of the column (in-case excel moans about it being the wrong size)
Set dest = objExcel.Activeworkbook.Sheets(1).Cells("A1")
Just saw that you tagged it as VBScript, I haven't tested it as VBS but it might work just the same as VBA.
For distinct copying .AdvancedFilter() method used, cells defined with getRange() from #NickSlash. For data addition from files, new sheet is created for each of them, and then data is filtered to it. I hope this helps.VBScript
Const xlFilterCopy = 2
Const xlUp = -4162
Const xlDown = -4121
strPathSrc = "C:\Test" ' Source files folder
strMaskSrc = "*.xlsx" ' Source files filter mask
iSheetSrc = 1 ' Sourse sheet index or name
iColSrc = 7 ' Source column index, e. g. 7 for "G"
strPathDst = "C:\Test\New Folder\4.xlsx" ' Destination file
iColDst = 1 ' Destination column index
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkBookDst = objExcel.Workbooks.Open(strPathDst)
Set objSheetTmp = objWorkBookDst.Worksheets.Add
objSheetTmp.Cells(1, iColDst).Value = "TempHeader"
Set objShellApp = CreateObject("Shell.Application")
Set objFolder = objShellApp.NameSpace(strPathSrc)
Set objItems = objFolder.Items()
objItems.Filter 64 + 128, strMaskSrc
objExcel.DisplayAlerts = False
For Each objItem In objItems
Set objWorkBookSrc = objExcel.Workbooks.Open(objItem.Path)
Set objSheetSrc = objWorkBookSrc.Sheets(iSheetSrc)
objSheetSrc.Cells(1, iColSrc).Insert xlDown
objSheetSrc.Cells(1, iColSrc).Value = "TempHeader"
Set objRangeSrc = GetRange(iColSrc, objSheetSrc)
If objRangeSrc.Cells.Count > 1 then
nNextRow = GetRange(iColDst, objSheetTmp).Rows.Count + 1
objRangeSrc.AdvancedFilter xlFilterCopy, , objSheetTmp.Cells(nNextRow, iColDst), True
objSheetTmp.Cells(nNextRow, iColDst).Delete xlUp
Set objRangeTmp = GetRange(iColDst, objSheetTmp)
Set objSheetDst = objWorkBookDst.Worksheets.Add
objRangeTmp.AdvancedFilter xlFilterCopy, , objSheetDst.Cells(1, iColDst), True
objSheetTmp.Delete
Set objSheetTmp = objSheetDst
End If
objWorkBookSrc.Close
Next
objSheetTmp.Cells(1, iColDst).Delete xlUp
objExcel.DisplayAlerts = True
Function GetRange(iColumn, objSheet)
With objSheet
Set GetRange = .Range(.Cells(1, iColumn), .Cells(.Cells(.Cells.Rows.Count, iColumn).End(xlUp).Row, iColumn))
End With
End Function
I think PasteSpecial will help with the pasting in vb script. It is best to use the -4163 argument in PasteSpecial to ensure that only the values are pasted. The code below worked for me in Microsoft Visual Studio 2012. Added comments just to know where the program is in the code. Hope this helps.
Imports System.Data.OleDb
Imports System.IO
Imports System.Text
Public Class Form1
Dim objCSV, objExcel, objSourceWorkbook, objDestWorkbook, objCSVWorkSheet, objXLSWorkSheet, srcCPUXrange, srcCPUYrange, srcMEMYrange, dstCPUXrange, dstCPUYrange, dstMEMYRange
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Create and open source CSV object
Label1.Text = "Setting Source"
objCSV = CreateObject("Excel.Application")
objCSV.Visible = True
objSourceWorkbook = objCSV.Workbooks.Open("C:\SourceFile.csv")
Label1.Text = "Source set"
'Create and open destination Excel object
Label1.Text = "Setting Destination"
objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objDestWorkbook = objExcel.Workbooks.Open("C:\DestinationFile.xlsx")
Label1.Text = "Destination Set"
'Select desired range from CSV file
Label1.Text = "Copying Data"
objCSVWorkSheet = objSourceWorkbook.Worksheets(1)
objCSVWorkSheet.Activate()
objSourceWorkbook.Worksheets(1).Range("A1").EntireColumn.Copy()
Label1.Text = "Data Copied"
'Paste in Excel workbook
Label1.Text = "Pasting Data"
objXLSWorkSheet = objDestWorkbook.Worksheets(1)
objXLSWorkSheet.Activate()
objDestWorkbook.Worksheets(1).Range("A2").PasteSpecial(-4163)
Label1.Text = "Data Pasted"
End Sub
End Class

Excel VBScript insert column and fill

I'm trying to insert a column to an Excel spreadsheet via a script. I found the code below which should allow me to insert a column, but how would I then go about filling that column with data like I would in the Excel application using the fill>down or fill>series commands?
Const xlToRight = -4161
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWB = objExcel.Workbooks.Open("C:\Temp\Scripts\Test2.xls")
Set objSheet = objwb.Sheets("Overall")
objSheet.Columns("D:D").Insert xlToRight
objWB.Close True
objExcel.Quit
EDIT
Here's what ended up working.
Const xlToRight = -4161
const xlColumns = &H2
const xlLinear = -4132
const xlDay = 1
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWB = objExcel.Workbooks.Open("C:\Temp\Scripts\Test2.xls")
Set objSheet = objwb.Sheets("Overall")
objSheet.Columns("A:A").Insert xlToRight
objSheet.Cells(1, 1).Value = "label"
objSheet.Cells(2, 1).Value = "Value"
set Range = objSheet.Range("A2:A"&objSheet.UsedRange.Rows.Count)
Range.FillDown
objSheet.Columns("A:A").Insert xlToRight
objSheet.Cells(1, 1).Value = "series"
objSheet.Cells(2, 1).Value = 1
set Range = objSheet.Range("A2:A"&objSheet.UsedRange.Rows.Count)
Range.DataSeries xlColumns, xlLinear,xlDay, 1, , False
objWB.Close True
objExcel.Quit
How To Insert a value into a Cell
The syntax (the object model) of using vbscript seems to be quite similar to excel VBA Macros.
objSheet.Cells(2,4).Value = "foo"
If you have any trouble finding something out it may work to create an excel macro using the built in macro recorder and take a look at the generated vba code - this helped me in the past to better understand excel vba macros. I assume that the vba code can be used in vbscript as well.

Selection.End(xlToRight) does not work

I am having a rough time getting this VBscript line to work with the excel object:
set fso=CreateObject("Scripting.FileSystemObject")
Set WShell = CreateObject("WScript.Shell")
Set objExcel = createobject("Excel.application")
objexcel.Visible = true
objexcel.Application.ScreenUpdating = True
objexcel.Workbooks.Open dir & masterFileName
objexcel.Activeworkbook.Worksheets("xActive_User_Ratio").Activate
objexcel.Range("A1").Select
objexcel.Range(Selection, Selection.End(xlToRight)).Select
when I run this code I get an error:
Object required: 'Selection'
What am I doing wrong? Any example would be very much helpful.
Please Help
It's because you are running this from outside Excel.
Use objExcel.Selection instead of just Selection. So that your code knows that Selection is associated with the Excel Application. Additionally, you'll need to define xlToRight or replace it with it's numerical value.
Better yet, I'd use with and rewrite the whole thing like so:
Set fso = CreateObject("Scripting.FileSystemObject")
Set WShell = CreateObject("WScript.Shell")
Set objexcel = CreateObject("Excel.application")
xlToRight = -4161 ' -4161 is the value of xlToRight
With objexcel
.Visible = True
.Application.ScreenUpdating = True
'using variables for workbook and worksheet to be explicit
Set wb = .Workbooks.Open(Dir & masterFileName)
Set ws = wb.Worksheets("xActive_User_Ratio")
ws.Activate
ws.Range("A1").Select
ws.Range(.Selection, .Selection.End(xlToRight)).Select
End With

Resources