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
Related
EDIT:
I started a new workbook and tore down the original code to test in a fresh environment. None of the OLEObjects.add methods seem to work even in this sanitized environment. I'm beginning to think that this method and parameters fundamentally do something other than what I think they do based on their documentation. I've included the parsed down code below along with a picture of what attaching a .pdf file looks like.
Sub AttachDocument()
'create cell location string
Dim celllocation As String
celllocation = ("D6")
'Select the cell in which you want to place the attachment
Range(celllocation).Select
'Get file path
'fpath = Application.GetOpenFilename("All Files,*.*", Title:="Select file")
'If LCase(fpath) = "false" Then Exit Sub
fpath = "C:\Users\Username\Desktop\2019W2.pdf"
'Insert file
Worksheets("Sheet1").OLEObjects.Add Filename:=fpath, Link:=False, DisplayAsIcon:=True, IconFileName:="EXCEL.EXE"
End Sub
I just don't understand why the parameters do not work. Any help is appreciated.
Original Post:
I have code that adds an OLEObject to a worksheet at a specific cell. It works, but I cannot get the parameters for OLEObjects.add method to do anything. The only one that seems to work is "Filename". No matter how I define any of the other parameters the behavior of the macro does not change; I'm not even sure the "Linked" parameter is working and the icon is always dependent on the file type uploaded but does not behave as expected(e.g. word documents do not display word icon, instead a large blank/white square). Ultimately, I want to set the icon to a common icon and define its size. What am I doing wrong here?
Sub AttachDocument()
'Check to make sure there is a selection for table row, if not end macro, also check for selection greater than the number of rows in the table, if yes end macro
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("RenewablesTable")
If Range("M3").Value < 1 Then
ElseIf Range("M3").Value > tbl.DataBodyRange.Rows.Count Then
Else
'create cell location string
Dim cellnum As Integer, celllocation As String
cellnum = Range("M3").Value + 8
celllocation = ("M" & cellnum)
'Select the cell in which you want to place the attachment
Range(celllocation).Select
'check if cell already has an object if it does end macro
If CheckCellforObject(celllocation) > 0 Then
Else
'Get file path
fpath = Application.GetOpenFilename("All Files,*.*", Title:="Select file")
If LCase(fpath) = "false" Then Exit Sub
'Insert file
Worksheets("Renewable Energy").Unprotect "password"
Worksheets("Renewable Energy").OLEObjects.Add Filename:=fpath, Link:=False, DisplayAsIcon:=True, IconFileName:="excel.exe"
Worksheets("Renewable Energy").Protect "password"
End If
End If
End Sub
I want to create a macro that can check and open file based on filename.
ex:
15.xlsm As opened workbook
12.xlsm As a target
16.xlsm As the future workbook
So while I click a button in 15.xlsm that will open the previous file (12.xlsm). But in future, when the 16.xlsm is created, the 16.xlsm must open the previous workbook (15.xlsm).
I was trying with this code
Sub Macro1()
Dim a, x As Integer
Dim path, filename As String
Dim varday, varyest As Long
varday = Day(Range("A1"))
For x = 1 To 30
varyest = varday - x
filename = "" & varyest & ".xlsm"
path = "F:\Kemal\" & filename & ""
If Dir(path) = "" Then
Else
Workbooks.Open filename:=path
End If
Next x
End Sub
but that code has open all workbook like 12.xlsm, 10.xlsm, 9.xlsm, and create unlimited messagebox. Yeah I know the algorithm but, how to put it into code is the big problem. anyone help me, pls.
So, How to check previous file is exist or not with date that placed on every workbook name?
to know if file exists :
CreateObject("Scripting.FileSystemObject").FileExists(p)
If you want to check MANY files, you may want to use the content of the whole folder and lookup the array.
if target workbooks has a Workbook_Open that's not to be launched:
Application.EnableEvents = False
workbooks.open(file)
Application.EnableEvents = true
Question is a bit fuzzy to me, I hope this answers
I have been trying to find the root cause of this issue for a long time, but to no avail.
I am trying to count the number of instances a specific text occurs in another workbook (in this case the instance is "42.1" and the workbook name will be contained in Filename1). For some reason, when I execute the countif directly in the sheet, it yields to the correct answer (which should be 2). But whenever I run the code below, it gives me 3.
All the references appear OK since I manually called each value from another workbook and there was no issue. Could you please help ?
Please diregard CounttIfV, it is essentially equivalent to the application function CountIf and I can use both interchangeably.
'manually define the latest S&OP input file
filename = Application.GetOpenFilename
Shapes("DisplayFilename").TextFrame.Characters.Text = filename
'activate the S&OP Workbook
Filename1 = Split(filename, "\")(UBound(Split(filename, "\")))
Workbooks.Open (Filename1)
Workbooks(Filename1).Activate
'define the correct S&OP worksheet regardless of the date
For Each ws_mould In ActiveWorkbook.Worksheets
If ws_mould.Name Like "*Mould*" Then
Worksheets(ws_mould.Name).Activate
active_ws = ws_mould.Name
End If
Next ws_mould
Workbooks(Filename1).Activate
Set CellRange = Workbooks(Filename1).Worksheets(active_ws).Range(Worksheets(active_ws).Cells(27, 45), Worksheets(active_ws).Cells(53, 45))
'NumBlades = Application.WorksheetFunction.CountA(CellRange)
NumBlades = Module3.COUNTIFv(CellRange, "??42.1#*")
Shapes("DisplayFilename").TextFrame.Characters.Text = active_ws
Someone asked this question: How do I create form controls (radio, checkbox, buttons, etc.) in Excel using Apache POI (Java)? before but no answers yet.
Also is it possible to make certain rows read only?
No not as far as i know, but you can create an Excel file with checkboxes that you can read back into Java using POI in this fashion:
Create an Excel file and save as template.xlsm (so with macro's).
Insert VBA macro in the Excel file (use 'Developer' tab) and save + close the file:
Sub addCheckBoxes()
Dim i As Integer
Dim cel As Range
i = 2
For Each cel In Sheets("Sheet1").Range("A" & 3 & ":A" & 1000)
i = i + 1
If Cells(i, "B").Value <> "" Then
cel.Value = 0
With ActiveSheet.OLEObjects.Add(ClassType:="Forms.CheckBox.1", Left:=cel.Left, Top:=cel.Top, Width:=cel.Width, Height:=cel.Height)
.LinkedCell = "Sheet1!$A$" & i
.Object.Caption = "<-use"
End With
End If
Next
End Sub
Let POI read this excel file as a new Workbook:
Workbook wb = WorkbookFactory.create(new File("path to your file/template.xlsm"));
Write all your data to the file (keep Column A empty for this example !). In this example we will add a checkbox to all cells in column 'A' that have a value/text in column 'B'. It checks every row from row 3 till 1000.
Write the Workbook to file:
FileOutputStream out = new FileOutputStream("path to your file/file_with_checkboxes.xlsm");
Create a file: start_excel_file.vbs add add the code as text:
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("path to your file/file_with_checkboxes.xlsm")
objExcel.Application.Visible = True
objExcel.Application.Run "file_with_checkboxes.xlsm!addCheckBoxes"
Use Java to open the file through the command line by running this file: start_excel_file.vbs
The code in the start_excel_file.vbs file will open the excel file and at start up it will create the checkboxes using the addCheckBoxes() Macro. (Macro's must be enabled !)
In this code i created a boolean text that is not visible in the Excel file but will be set to TRUE if selected and FALSE is unselected afterwards. If you read the file with POI back into Java it will ignore the checkboxes but is able to read the boolean text so in Java you know what was/is the setting. (empty or FALSE = false / TRUE is true)
hope this helps and good luck =^)
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"