Error when trying to format an Excel column with vbScript - excel

I am using vbScript to run a procedure on an MS Excel file. The goal of this procedure is 4 fold.
Remove all "-"'s from Column C in the file
Format Column C as "000000000" (this column contains social security numbers, when I remove the dashes I want to preserve the leading zeroes)
Format Column E as "yyyymmdd"
Save the file
The below code is what I am using. I am able to achieve Goal #1 and Goal #3 perfectly. I am unable to achieve the 2nd goal, basically once I remove the "-"'s the values do not reflect the leading zeroes. When it comes to goal #4, the Save As dialogue box pops up and I am forced to manually save. I do not want this, rather I want the file to just save in the same location with the same file name.
Const FromValue = "-"
Const ToValue = ""
Dim objExcel : Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\charlie-tufts\Desktop\Practice Reports\VCA Termination Report Result.csv")
Dim objWorksheet : Set objWorksheet = objWorkbook.Worksheets(1)
Dim objRangeSSN : Set objRangeSSN = objWorksheet.range("C:C")
Dim objRangeDate : Set objRangeDate = objWorksheet.range("E:E")
objRangeSSN.Replace FromValue, ToValue
objRangeSSN.numberformat = "000000000"
objRangeDate.numberformat = "yyyymmdd"
objExcel.DisplayAlerts = False
objExcel.Save
objExcel.Quit
Thank you in advance for your help!
-Charlie

Related

VBScript Importing .txt file to .xlsx file [duplicate]

I'm trying to convert pipe-delimited files to xls (Excel) with batch file and vbscript. Unfortunately, my "output.xls" file is still showing the pipe delimiter in the table and the data are not organized.
srccsvfile = Wscript.Arguments(0)
tgtxlsfile = Wscript.Arguments(1)
'Create Spreadsheet
'Look for an existing Excel instance.
On Error Resume Next ' Turn on the error handling flag
Set objExcel = GetObject(,"Excel.Application")
'If not found, create a new instance.
If Err.Number = 429 Then '> 0
Set objExcel = CreateObject("Excel.Application")
End If
objExcel.Visible = false
objExcel.displayalerts=false
'Import CSV into Spreadsheet
Set objWorkbook = objExcel.Workbooks.open(srccsvfile)
Set objWorksheet1 = objWorkbook.Worksheets(1)
'Adjust width of columns
Set objRange = objWorksheet1.UsedRange
objRange.EntireColumn.Autofit()
'This code could be used to AutoFit a select number of columns
'For intColumns = 1 To 17
' objExcel.Columns(intColumns).AutoFit()
'Next
'Make Headings Bold
objExcel.Rows(1).Font.Bold = TRUE
'Freeze header row
With objExcel.ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
objExcel.ActiveWindow.FreezePanes = True
'Add Data Filters to Heading Row
objExcel.Rows(1).AutoFilter
'set header row gray
objExcel.Rows(1).Interior.ColorIndex = 15
'-0.249977111117893
'Save Spreadsheet, 51 = Excel 2007-2010
objWorksheet1.SaveAs tgtxlsfile, 51
'Release Lock on Spreadsheet
objExcel.Quit()
Set objWorksheet1 = Nothing
Set objWorkbook = Nothing
Set ObjExcel = Nothing
source :http://www.tek-tips.com/viewthread.cfm?qid=1682555
Pipe doesn't equal Comma, Excel natively knows what to do with a CSV, but not with Pipe.
All is not lost, record your actions opening the file manually, once open highlight column A and click Data / Text To Columns, choose delimited and in the "other" box put a pipe then click next, choose the column formats (great to format numbers as text if you need to like Postcodes and phone numbers) then click finish.
Now stop the recorder and look at the code it generated. Port this over to your Excel object in your script.
Excel is a little picky when it comes to reading CSV files. If you have a delimited file with the extension .csv Excel will only open it correctly via the Open method if the delimiter is the character configured in the system's regional settings.
The Open method has optional parameters that allow you to specify a custom delimiter character (credit to #Jeeped for pointing this out):
set objWorkbook = objExcel.Workbooks.Open(srccsvfile, , , 6, , , , , "|")
You can also use the OpenText method (which will be used when recording the action as a macro):
objExcel.Workbooks.OpenText srccsvfile, , , 1, , , , , , , True, "|"
Set objWorkbook = objExcel.Workbooks(1)
Note that the OpenText method does not return a workbook object, so you must assign the workbook to a variable yourself after opening the file.
Important: either way your file must not have the extension .csv if your delimiter character differs from your system's regional settings, otherwise the delimiter will be ignored.

Run-Time Error '9': Subscript Out of Range when generating spreadsheet

I am currently trying to use an access database which uses vba to generate Excel spreadsheets and AutoCAD drawings; I didn't write the code, and I don't have experience coding in this language. When generating an excel file, the code gets to the line MyXL.Parent.Windows(1).Visible = True, it gives the error. The excel file is generated, but is identical to the template.
The File and directory names are placeholders
Dim MyXL As Object
FileCopy "\Directory\Template", "\Directory\Filename"
' This copies an Excel file, first half, then renames it with the Sales order number
Set MyXL = GetObject("\Directory\Template")
' This opens the Excel file named in the upper code second half
MyXL.Application.Visible = True
MyXL.Application.WindowState = 3
' MyXL1.Activate
MyXL.Parent.Windows(1).Visible = True
MyXL.Parent.ActiveWindow.WindowState = 2
With MyXL.Worksheets(1)
End With
At this point it sets a lot of values (I assume) in the form .Range("T60").Value = Me![Text516]
MyXL.Worksheets(1).Activate
MyXL.Save
MyXL.Parent.Quit ' This is what you have to do to close the Application
'MyXL.Parent.Quit
' MyXL.Parent.ActiveWindow.WindowState = xlMinimized
' MyXL.Close
The possible duplicate relates to copying an excel spreadsheet, however this problem goes further than that
Edit: I made a mistake and previously had the line Set MyXL = GetObject("\SameDirectory\SameFilename") but it is actually Set MyXL = GetObject("\Directory\Template")
Example of working code to open an Excel workbook, edit, save to a new name.
Sub CopyExcel()
Dim xl As Excel.Application, xlw As Excel.Workbook
Set xl = CreateObject("Excel.Application")
'the following two lines have same result
Set xlw = xl.Workbooks.Open("C:\Users\June\MyStuff\Condos.xlsx", , True)
'Set xlw1 = xl.Workbooks.Add("C:\Users\June\MyStuff\Condos.xlsx")
'code to edit
xlw.SaveAs "C:\Users\June\MyStuff\Condos2.xlsx"
xl.Quit
End Sub

Read live Values from one Excel Workbook to another Workbook while opened

I would like to be able to read and write values using VBA from one OPEN Excel workbook to another application without using the "as worksheet" function due to this being a non-windows application. Is this possible?
The code I've posted is from a PLC application using scripting.
I just need to know what function to use besides .open since the file is already opened.
Dim objXLApp, objXLWb, objXLWs1, objXLWs2, objXLWs5
Set objXLApp = CreateObject("Excel.Application")
objXLApp.Visible = True
Set objXLWb = objXLApp.Workbooks.Open("File.xlsm")
'~~> Working with Sheet1
Set objXLWs1 = objXLWb.Sheets(1)
Set objXLWs2 = objXLWb.Sheets(2)
Set objXLWs5 = objXLWb.Sheets(5)
'~~>Write SetPoints to Sheet1
With objXLWs1
'~~>Write
.Cells(6,23).value = SmartTags("Job Time Sec to OEE")
.Cells(6,23).value = SmartTags("Run Time Sec to OEE")
End With
''~~>Write Setup Values to Sheet2
'~~> Save as Excel File (xls) to retain format
objXLWb.Save
objXLWb.Close (False)
Set objXLWs1 = Nothing
Set objXLWs2 = Nothing
Set objXLWs5 = Nothing
Set objXLWb = Nothing
objXLApp.Quit
Set objXLApp = Nothing
If the workbook is already open you can just refer to it by name as part of the Workbooks collection.
Set objXLWb = objXLApp.Workbooks("File.xlsm")
Edit: Since you have changed your question I'm no longer certain what you're asking. My guess is that your 'already open' workbook isn't open in the same Excel instance you're creating with Set objXLApp = CreateObject("Excel.Application"), so you'll need a reference to the existing Excel application, then the open workbook within that application.

Convert pipe-delimited files to .xls

I'm trying to convert pipe-delimited files to xls (Excel) with batch file and vbscript. Unfortunately, my "output.xls" file is still showing the pipe delimiter in the table and the data are not organized.
srccsvfile = Wscript.Arguments(0)
tgtxlsfile = Wscript.Arguments(1)
'Create Spreadsheet
'Look for an existing Excel instance.
On Error Resume Next ' Turn on the error handling flag
Set objExcel = GetObject(,"Excel.Application")
'If not found, create a new instance.
If Err.Number = 429 Then '> 0
Set objExcel = CreateObject("Excel.Application")
End If
objExcel.Visible = false
objExcel.displayalerts=false
'Import CSV into Spreadsheet
Set objWorkbook = objExcel.Workbooks.open(srccsvfile)
Set objWorksheet1 = objWorkbook.Worksheets(1)
'Adjust width of columns
Set objRange = objWorksheet1.UsedRange
objRange.EntireColumn.Autofit()
'This code could be used to AutoFit a select number of columns
'For intColumns = 1 To 17
' objExcel.Columns(intColumns).AutoFit()
'Next
'Make Headings Bold
objExcel.Rows(1).Font.Bold = TRUE
'Freeze header row
With objExcel.ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
objExcel.ActiveWindow.FreezePanes = True
'Add Data Filters to Heading Row
objExcel.Rows(1).AutoFilter
'set header row gray
objExcel.Rows(1).Interior.ColorIndex = 15
'-0.249977111117893
'Save Spreadsheet, 51 = Excel 2007-2010
objWorksheet1.SaveAs tgtxlsfile, 51
'Release Lock on Spreadsheet
objExcel.Quit()
Set objWorksheet1 = Nothing
Set objWorkbook = Nothing
Set ObjExcel = Nothing
source :http://www.tek-tips.com/viewthread.cfm?qid=1682555
Pipe doesn't equal Comma, Excel natively knows what to do with a CSV, but not with Pipe.
All is not lost, record your actions opening the file manually, once open highlight column A and click Data / Text To Columns, choose delimited and in the "other" box put a pipe then click next, choose the column formats (great to format numbers as text if you need to like Postcodes and phone numbers) then click finish.
Now stop the recorder and look at the code it generated. Port this over to your Excel object in your script.
Excel is a little picky when it comes to reading CSV files. If you have a delimited file with the extension .csv Excel will only open it correctly via the Open method if the delimiter is the character configured in the system's regional settings.
The Open method has optional parameters that allow you to specify a custom delimiter character (credit to #Jeeped for pointing this out):
set objWorkbook = objExcel.Workbooks.Open(srccsvfile, , , 6, , , , , "|")
You can also use the OpenText method (which will be used when recording the action as a macro):
objExcel.Workbooks.OpenText srccsvfile, , , 1, , , , , , , True, "|"
Set objWorkbook = objExcel.Workbooks(1)
Note that the OpenText method does not return a workbook object, so you must assign the workbook to a variable yourself after opening the file.
Important: either way your file must not have the extension .csv if your delimiter character differs from your system's regional settings, otherwise the delimiter will be ignored.

VB Script to copy all sheet data one excel to another excel sheet

Is it possible to copy data from all the workbook sheets from one excel sheet (ex: A.xls) to another existing excel (ex: B.xls).
Can a logic be implemented, using VB, where it can do that no matter the amount of workbook sheets in A.xls (i.e. It should copy all the data of all pages of A.xls to B.xls)
I appreciate any kind of help, for I am not from a programming background.
Though I'm starting to think you want to copy all the data across many tabs to one tab, if you actually want to keep the data on separate tabs, you can use something like this to loop through the worksheets in A.xlsx and copy them to B.xlsx:
Sub copy_sheets()
Dim eapp As Excel.Application
Dim wkbk_from As Workbook
Dim wkbk_to As Workbook
Dim wksh As Worksheet
Set eapp = CreateObject("Excel.Application")
Set wkbk_from = eapp.Workbooks.Open("C:\Documents\Miscellaneous-DT\Excel\a.xlsx")
Set wkbk_to = eapp.Workbooks.Open("C:\Documents\Miscellaneous-DT\Excel\b.xlsx")
eapp.Visible = True
For Each wksh In wkbk_from.Worksheets
wksh.Copy After:=wkbk_to.Worksheets(Worksheets.Count)
Next wksh
End Sub
Well After a lot of struggle and learning some basics i was able to get the code
Here is the code which works
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objPasteData = objExcel.Workbooks.Open("C:\A.xlsx") 'Copy From File
Set objRawData= objExcel.Workbooks.Open("C:\B.xls") 'Paste To File
Set obj1 = objPasteData.WorkSheets("RawData") 'Worksheet to be cleared
obj1.Cells.Clear
countSheet = objRawData.Sheets.Count
For i = 1 to countSheet
objRawData.Activate
name = objRawData.Sheets(i).Name
objRawData.WorkSheets(name).Select
objRawData.Worksheets(name).Range("A2").Select
objExcel.ActiveSheet.UsedRange.Select
usedRowCount1 = objExcel.Selection.Rows.Count
objExcel.Range("A2:H" & usedRowCount1).Copy
objPasteData.Activate
objPasteData.WorkSheets("RawData").Select
objExcel.ActiveSheet.UsedRange.Select
usedRowCount2= objExcel.Selection.Rows.Count
objPasteData.Worksheets("RawData").Range("A"& usedRowCount2 + 1 ).PasteSpecial Paste =xlValues
Next
objPasteData.Save
Thanks #Nilpo & #rryanp for guidance.
The easiest way to copy all data from one worksheet to another is to use the copy and paste operation on a range that consists of all filled cells.
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook1= objExcel.Workbooks.Open("C:\test1.xls")
Set objWorkbook2= objExcel.Workbooks.Open("C:\test2.xls")
Set objRange = objWorkbook1.Worksheets("Sheet1").UsedRange.Copy
objWorkbook2.Worksheets("Sheet1").Range("A1").PasteSpecial objRange
objWorkbook1.Save
objWorkbook1.Close
objWorkbook2.Save
objWorkbook2.Close
You say existing file b.xls, wbut if you overwrite everything, it doesn't matter so why not use
CreateObject("Scripting.FileSystemObject").CopyFile "a.xls", "b.xls", true
I had the same task yesterday and had to spent a lot of time searching for the parts of the solution. From some reason in vbs named constants are not available (at least in newer Excel versions).
The script below is tested and prooved to be working in newer Excel (2016)
outputFiletype = 51 'type_xlsx
' I assume you want to use the script for different files, so you can pass the name as a parameter
If Wscript.Arguments.Count < 1 Then
Wscript.Echo "Please specify a name of the Excel spreadsheet to process"
Else
inputFilename = Wscript.Arguments(0)
outputFilename = Replace(inputFilename, ".xlsx", "_calc.xlsx")
Set objExcel = CreateObject("Excel.Application")
objExcel.DisplayAlerts = False
' if you want to make the excel visible (otherwise if it is failed it will hang in a process list)
'objExcel.Application.Visible = True
Set currentWorkbook = objExcel.Workbooks.Open(inputFilename)
Set newWorkbook = objExcel.Workbooks.Add()
i = 0
For Each current_sheet In currentWorkbook.Worksheets
If current_sheet.Visible Then ' copying only the visible ones
i = i + 1
Dim new_sheet
If newWorkbook.Sheets.Count < i Then
newWorkbook.Sheets.Add , newWorkbook.Sheets(i-1) ' after the last one
End If
Set new_sheet = newWorkbook.Sheets(i)
new_sheet.Name = current_sheet.Name
current_sheet.UsedRange.Copy
new_sheet.Select
new_sheet.UsedRange.PasteSpecial 13 'xlPasteAllUsingSourceTheme - Everything will be pasted using the source theme
new_sheet.UsedRange.PasteSpecial 8 'xlPasteColumnWidths - Copied column width is pasted
new_sheet.UsedRange.PasteSpecial 12 'xlPasteValuesAndNumberFormats - Values and Number formats are pasted.
End If
Next
newWorkbook.SaveAs outputFilename, outputFiletype
currentWorkbook.Close False
newWorkbook.Close False
objExcel.Quit
End If

Resources