Error when using Workbooks - excel

I would like to develop a method to ensure that information is copied from 1 workbook (ThisWorkbook) and is pasted in another workbook (All data.xlsm) on empty rows. I was able to develop the code if the 2 sheets are in the same workbook, but now that I need to refer to another workbook it doesn't work (error 9). The difficulty is also that both workbooks are on a teamsite, but both files are open.
Please find below my code (with my best attempt).
Dim actionlogRow
Dim actionlogRowSet As Boolean
Dim RecordSave As String
Dim recordActionLog As String
actionlogRow = 1
actionlogRowSet = False
Application.ScreenUpdating = False
RecordSave = Range("new_actions").Cells(1, 1).Value
Workbooks("All data.xlsm").Activate
Do
recordActionLog = Worksheets("Action Log").Range("C8:AE8").Offset(actionlogRow, 0).Cells(1, 1)
If recordActionLog = "" Then
'Location to copy to is current row
actionlogRowSet = True
Else
'Look at next row
actionlogRow = actionlogRow + 1
End If
Loop Until actionlogRowSet = True
'Copy the record into the database
Call ThisWorkbook.Sheets("New actions").Range("new_actions_endorsed").Copy
Call Workbooks("All data.xlsm").Worksheets("Action Log").Range("C8:AE8").Offset(actionlogRow, 0).PasteSpecial(xlPasteValuesAndNumberFormats)
Application.ScreenUpdating = True

You must have both spreadsheets open in the same instance of Excel. If you open Excel first, then open both spreadsheets from that (Ctrl O) you should be fine. However if you open two Excel program files, they cannot see each other and you will get "Run-time error 9: Subscript out of range"

Related

Issue copying number from one xlsm to another via VBA

I'm attempting to reset some cells in an xlsm and then copy a single cell from one workbook to another via a VBA macro. Code is below:
Range("E19").Copy
Range("E6").PasteSpecial xlPasteValues
Range("E5").Value = 0
Range("E8:E9").Value = 0
Range("E11:E12").Value = 0
Range("E25:E28").Value = 0
Range("E30").Value = 0
Range("I25:I31").Value = 0
Range("G2").Clear
Dim ubbPrevDay As Single
Dim objWorkbook As Workbook
'open the workbook with data
Set objWorkbook = Workbooks.Open("<file path censored for privacy>")
ubbPrevDay = objWorkbook.Worksheets("UBB").Range("C13")
'close the workbook
objWorkbook.Close SaveChanges:=False
Range("E4") = ubbPrevDay
Dim name As String
name = InputBox("Enter your name")
Range("G2").Value = name
The operation runs and copies a value, but occasionally copies the decimal just a little bit incorrectly. Today it copied '550687.88' as '550687.875'. I verified that the data on the workbook being copied is correct so something is getting altered in the macro process. Any advice is greatly appreciated.
-Kevin

Extract checkbook value from a closed spreadsheet using Excel VBA

I have a fairly larger number of excel workbooks in a folder. Each workbook has one tab - Sheet1. Sheet1 includes three checkboxs: Checkbox 6, Checkbox 7 and Checkbox 8 in addition to some values in cells. I'm using this code:
Link to Code Used
to extract the cell values, but was hoping it would also be possible to determine the value (status checked or not checked) of each of the checkboxes. Is this possible? Note - None of the checkbox are linked to a particular cell.
There is no way to read anything from a closed file. Even the code you are linking to cannot do this. You will always need a program that opens the file, read the data from it, find the information you want and close it again.
For Excel files you usually use Excel, but it could be something else - I know that Python has an library to read & write Excel files (and there are more), but all of them have to open the file. Open means ask the operating system to read the data from disk, maybe set a lock, maybe later write it back, those kind of things.
That said, what you probably want is to access the data (in your case checkbox settings) without the sheet being visible. You can do so by set Application.ScreenUpdating = False, open the file, read the checkbox values, close the file and reset Application.ScreenUpdating = True. The user will not see anything. I strongly assume that the Excel4-Macro does the same, but you will not find many persons around that are able to deal with Excel4-Macros.
Now to be able to read the value of a checkbox, you need to know if you are dealing with ActiveX or Form controls (or both). I wrote a small prove of concept that can deal with both. You pass the name of a workbook, the name (or number) of a sheet and an array with the name of the checkboxes you want to read. Result is an array with the values of the checkboxes. However you need to know that the values of an ActiveX-checkbox is True or False (or Null if you allow TripleState), while for a form-checkbox it is xlOn or xlOff. In the case a sheet doesn't have a checkbox with the specific name, it will return an arbitrary number
Function getCheckBoxValueFromFile(filename As String, sheet As Variant, checkboxNames) As Variant
Const undefinded = -999
Application.ScreenUpdating = False
Dim wb As Workbook
Set wb = Workbooks.Open(filename)
Dim i As Integer, res()
ReDim res(LBound(checkboxNames) To UBound(checkboxNames))
For i = LBound(checkboxNames) To UBound(checkboxNames)
Dim val As Long
val = undefinded
With wb.Sheets(sheet)
On Error Resume Next
' first try ActiveX-CheckBox
val = .OLEObjects(checkboxNames(i)).Object.Value
' if failed, try Form-CheckBox
If val = undefinded Then val = .CheckBoxes(checkboxNames(i)).Value
On Error GoTo 0
res(i) = val
End With
Next i
wb.Close False
getCheckBoxValueFromFile = res
Application.ScreenUpdating = True
End Function
To test the function:
Sub test()
Dim res, i, cbNames
cbNames = Array("CheckBox1", "Check Box 2")
res = getCheckBoxValueFromFile("C:\TEMP\Book1.xlsx", "Sheet1", cbNames)
For i = LBound(res) To UBound(res)
Debug.Print i & ": " & cbNames(i) & " -> " & res(i)
Next i
End Sub

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

Excel Crashes, Repairs and Restarts itself when I delete worksheets programmatically

I have an issue with my excel. To begin with, I create worksheets dynamically based on some parameters and then I export the worksheets as PDF. So far everything is fine. Now, when I am done with worksheets and I don't need them anymore I want to delete them. When I run the code excel crashes, repairs and then restarts itself. I am wondering if anyone has any idea why this keeps happening. I also delete named ranges for each sheet just in case.
Btw, if I delete them manually everything is fine.
Here's the code
Application.DisplayAlerts = False
Dim theName As Name
Dim newSheet As Worksheet
For i = 1 To unitsQty
Set newSheet = ThisWorkbook.Worksheets("Project Info " & i)
For Each theName In Names
If (TypeOf theName.Parent Is Worksheet) And (newSheet.Name = theName.Parent.Name) Then
theName.Delete
End If
Next
Set newSheet = ThisWorkbook.Worksheets("System Spec " & i)
For Each theName In Names
If (TypeOf theName.Parent Is Worksheet) And (newSheet.Name = theName.Parent.Name) Then
theName.Delete
End If
Next
Next i
Dim myArray() As Variant
ReDim myArray(unitsQty * 2)
With Sheets("Tables")
For i = 1 To unitsQty
myArray(i - 1) = "Project Info " & i
Debug.Print myArray(i)
Next i
For i = 1 To unitsQty
myArray(i - 1 + unitsQty) = "System Spec " & i
Debug.Print myArray(i)
Next i
End With
ThisWorkbook.Sheets(myArray(0)).Select
ThisWorkbook.Sheets(myArray).Select
ThisWorkbook.Sheets(myArray((unitsQty * 2 - 1))).Activate
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = True
thanks for your help. So basically in the worksheets I had OLE Object and therefore every time I was trying to delete a worksheets I had "Can't enter break mode at this time" and when I clicked continue but excel was crashing.
Even when I tried to delete all objects from the worksheet before i deleted it, excel still crashing.
I couldn't find any solution in the web, but I found a workaround that it is working fine and gives the desired results. The workaround is to copy the worksheets to a temp workbook and do all the work there and when I am done, i am just closing the workbook without saving it of course. That keeps my original workbook tidied up.

Outlook Excel Compare data from two closed workbooks

I am new to Outlook VBA and am trying to compare the value in the same cell from two different closed workbooks.
I have created an Excel Object upon receiving an attachment from an email that saves the attachment as a CSV file.
I then want to check that the header row within the file matches a master copy which has the same headers in the first row but I am not sure how to reference the sheet names nor the cells using the objects.
I have tried many ways using VBA for Excel but it doesn't seem to work in Outlook.
If any one can assist me it would be greatly appreciated.
Function ConvertXls2CSV(sXlsFile As String)
On Error Resume Next
Dim oExcel As Object
Dim oExcelWrkBk As Object
Dim bExcelOpened As Boolean 'Was Excel already open or not
Dim OriginalFile As String
Dim MasterFile As String
Dim Fault As Integer
Set oExcel = GetObject(, "Excel.Application") 'Bind to existing instance of Excel
If Err.Number <> 0 Then 'Could not get instance of Excel, so create a new one
Err.Clear
On Error GoTo Error_Handler
Set oExcel = CreateObject("excel.application")
bExcelOpened = False
Else 'Excel was already running
bExcelOpened = True
End If
Set oExcelWrkBk = oExcel.Workbooks.Open(sXlsFile)
oExcelWrkBk.SaveAs Left(sXlsFile, InStrRev(sXlsFile, ".")) & "csv", xlCSVWindows
/*THIS IS WHERE I WANT TO REFERENCE THE CELLS IN THE WORKBOOKS*/
OriginalFile = oExcelWrkBk.Sheets("PK Price Data").Cells(1, 1).Value
MasterFile = oExcelWrkBk."MasterFile.xls".Sheets("PK Price Data").Cells(1, 1).Value
if OriginalFile = MasterFile then
fault = 1
else fault = 0
end if
oExcelWrkBk.Close False
If bExcelOpened = False Then
oExcel.Quit
End If
End Function
Many Thanks
Melinda
As far as I know, it's not possible to address your references to a closed workbook. You can, however, open it without showing with application.screenupdating = false. When you're done storing your references in some variables, you can simply close the workbooks and set application.screenupdating = true

Resources