VBA - File copy inherits read-only mode - excel

I have an MS Access application that uses VBA for a number of things. I need to add a row to an excel spreadsheet before auto-importing the data - trust me there is no better way in this case. Right now, this works as long as the spreadsheet isn't open by someone. However, if it is, I can't modify the spreadsheet and I get the pop-up of the spreadsheet in read-only mode. To get around this, I added code to copy the existing spreadsheet to a temp folder and set the "Read-only" value to normal. This SHOULD work - I think. However, even when I try this, I still get the read-only error. YET, when I check the value of my TEMP file, it's not set to read-only!!!
I'm guessing that read-only is really "locked by another user."
How can I accomplish my goal of getting access to edit that file / a temp copy?
Below is the code where I get the message:
Dim fso as Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Call fso.CopyFile(myOriginalFolderFile, myTempFolderFile)
' copyfile works successfully
SetAttr myTempFolderFile, vbNormal
' still no error
Dim my_xl_app as Object
Dim my_xl_worksbook as Object
Set my_xl_app = CreateObject("Excel.Application")
Set my_xl_workbook = my_xl_app.Worksbooks.Open(myTempFolderFile)
' this is where it throws the message

In the Save dialog box, there is a TINY option for "Tools" and "General Options" and it has a checkbox next to ‘Read-only recommended’.

Related

How to open an embedded object in spreadsheet as read only through excel VBA

I have few objects embedded in a hidden sheet in workbook which runs the VBA code. These objects (word, excel, pdf etc.) are just the templates and I need to open a copy of these or open these as read only upon a click on a command button, so that the template content remains same.
I have searched over the internet but did not find a way to open these embedded objects as read only. I am running this code but save as operation is not successful.
Private Sub M114_Click()
Dim WDObj As Object
Dim WDApp As Object
Set WDApp = GetObject(, "Word.Application")
Set WDObj = Sheets("Tools").OLEObjects("MO")
WDObj.Activate
WDApp.ActiveDocument.SaveAs ("MO_copy.doc")
Set WDObj = Nothing
Set WDApp = Nothing
End Sub
You need to protect the document to prevent changes before you embed it in Excel.
With the example of a Word Document:
You can use Word's protection functionality to protect it, and could optionally give different rights to different users.
Go to the Review tab on the ribbon.
In the Protect group, click Restrict Editing
In section 2 of the Restrict Editing options on the side of the screen, check the box that says "Allow only this type of editing" and make sure the dropdown is set to **No Changes (Read Only)**.
Set other protection options as desired.
In section 3 click Yes, start enforcing.
Save & close the document and then embed in your Excel file.
Alternatively, if your embedded object is linked to the source file, you can set the file to Read Only in the Windows file properties. This won't work if the object isn't linked to the file.

How to open and edit an excel template using visual basic

I have a template that we use at work that I want to edit using visual basic. I have a gui built that asks the user for a few pieces of data. I need to open the template and just edit the contents of the template based on the user input. I have done research so far and everything I've seen shows me how to open a new excel document, not a current one. How do I open the current template?
*I get the user to browse for and select the filename and have that stored as a variable
Hard to say what you want to achieve maybe more clarification is needed.
To reference an Opened Excel file
Set execlObj = GetObject(fileName)
To open an Unopened Excel file (in separate Excel application)
Dim oXLApp As Object, wb As Object
Set oXLApp = CreateObject("Excel.Application")
Set wb = oXLApp.Workbooks.Open(fileName)
Where file name is e.g. c:\test.xls

Creating Word Application using Excel VBA: Run-time error '429': ActiveX component can't create object

I am trying to save Word docs using Excel VBA, but I get the error
"ActiveX component can't create object."
When I debug, the error comes from the line: Set wrdApps = CreateObject("Word.Application").
It was working, then it started giving me this error.
Sub saveDoc()
Dim i As Integer
For i = 1 To 2661:
Dim fname As String
Dim fpath As String
With Application
.DisplayAlerts = False
.ScreenUpdating = False
.EnableEvents = False
End With
fname = ThisWorkbook.Worksheets(3).Range("H" & i).Value
fpath = ThisWorkbook.Worksheets(3).Range("G" & i).Value
Dim wrdApps As Object
Dim wrdDoc As Object
Set wrdApps = CreateObject("Word.Application")
'the next line copies the active document- the ActiveDocument.FullName
' is important otherwise it will just create a blank document
wrdApps.documents.Add wrdDoc.FullName
Set wrdDoc = wrdApps.documents.Open(ThisWorkbook.Worksheets(3).Range("f" & i).Value)
' do not need the Activate, it will be Activate
wrdApps.Visible = False
' the next line saves the copy to your location and name
wrdDoc.SaveAs "I:\Yun\RTEMP DOC & PDF\" & fname
'next line closes the copy leaving you with the original document
wrdDoc.Close
On Error GoTo NextSheet:
NextSheet:
Resume NextSheet2
NextSheet2:
Next i
With Application
.DisplayAlerts = True
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
I had an issue when upgrading from Windows 7 to 10 when bringing my hoard of VBA scripts with me.
Still not sure what the root cause of the error is, but in the mean time this piece of code worked for me.
This is a workaround that limits the need to have Word (or Outlook/Excel) already in open (manually) state, but should allow your script to run if you have your references set.
Just change "CreateObject(" to "GetObject(, ". This will tell the system to use an already open window.
The complete code to use would be:
Dim wrdApps As Object
Dim wrdDoc As Object
Set wrdApps = GetObject(, "Word.Application")
I recently had this happen to some code I had written. Out of nowhere (after running successfully for a few months), I would get the same Runtime Error '429'. This happened on two separate computers, the one I wrote and tested the code on months prior and the computer of the person who actually used the tool. It happened even though I used the original file on my machine and the user had been using his copy successfully for a few months, so I'm not convinced two separate files on two separate machines both got corrupted in the same manner. With that being said, I don't have a good explanation of why this occurred. Mine would happen on a similar line of code:
Dim objFSO as Object
Set objFSO = CreateObj("Scripting.FileSystemObject")
I had the reference to the scripting library included and had done this successfully in the past.
I was able to fix the problem by changing from late to early binding on that object:
Dim objFSO as New Scripting.FileSystemObject
I have been switching everything over to early binding for some time now but this was some legacy code. A nice short little explanation on the difference between the two can be found here:
https://excelmacromastery.com/vba-dictionary/#Early_versus_Late_Binding
I'm not entirely certain why that fixed the problem, but hopefully it will help others in the future with similar issues.
Is wrdDoc initialised? Are you trying to use wrdDoc before the object has been Set?
wrdApps.documents.Add wrdDoc.FullName
Set wrdDoc = wrdApps.documents.Open(ThisWorkbook.Worksheets(3).Range("f" & i).Value)
Should the first line be ActiveDocument.FullName as in the comments? So:
wrdApps.documents.Add ActiveDocument.FullName
Check that you have the Microsoft Excel Object Library and the Microsoft Office Object Library ticked in Tools > References and that they have been registered.
If they are ticked, you may need to run Detect and Repair from the Excel Help menu to make sure that the Office installation hasn't corrupted in any way.
In my case, the workbook appeared to be corrupted. Simply assigning a worksheet to a variable was throwing the error.
Dim ws as Worksheet
Set ws = ThisWorkbook.Worksheets("Data")
The workbook came directly from the client, so I'm not sure what they did with it, or how old it was but all the references appeared to be selected. Every other workbook with the same code was working correctly.
So to resolve the issue I copied the worksheets and modules to a new workbook and it worked without any issues.
Might not always be the best solution, but if you haven't got any worksheets and modules, then it's pretty easy.
It's seems to be linked to the presence of a second "ThisWorkbook" object, in my case.
Excel VBA Project has generated multiple Workbook objects
No other solution found that the one in this link. I didn't try it myself, though.
Try this one.. i've encountered this a lot of time...
so I just run my excel by searching it (located on taskbar), then right click then "run as administrator"
or if you already created the excel file, open it from file>open>browse. avoid just double clicking the excel file to open directly.

Get table data in Excel 2007 from query in Access 2007

I have an automated process that is mostly run in Access. But, in the middle, it puts some data in Excel to scrub it into the correct form (it's much faster than doing it in Access), and at the end it opens another Excel file and puts data from some Access queries into the Excel file. For these connections from Excel to Access, I accomplished them all by going into Excel and doing Data --> Get External Data --> From Access, then selecting the Access file and the query I want to get the data from and tell Excel to make it into a Table.
So, I do that one time and then I want to be able to run this automated process that simply refreshes the data. To do this refreshing of the data, I do a line like:
Worksheets("Data").Range("A1").ListObject.QueryTable.Refresh _
BackgroundQuery:=False
The problem is, half the time (and I can't figure out why it does it one time and not another), it says "Do you want to connect to path\filename?" Of course I do, how else would the table refresh? So, this stops the automation. Even if I click Yes, I still can't get it to continue on. If I click Yes, it opens up the Data Link Properties. After I click OK for that, it opens a window titled "Please Enter Microsoft Office Access Database Engine OLE DB Initialization Information". It has info in it, including the path and name of the data source I want to access, but if I click OK, it says, sorry that didn't work, would you like instead to connect to (and then it lists the exact same path and file name it just said didn't work). It repeats the steps I just mentioned, and after that it errors out.
In case it matters, here is the (basic idea) code I use to connect to Excel from Access:
Public Sub ExportToExcel()
Dim ObjXLApp As Object
Dim ObjXLBook As Object
Dim ExcelFilePath As String
ExcelFilePath = CurrentProject.Path & "\"
Set ObjXLApp = CreateObject("Excel.Application")
Set ObjXLBook = ObjXLApp.Workbooks.Open(ExcelFilePath & "filename.xlsm")
ObjXLApp.Visible = True
' Runs the "DataSetUp" macro in the Excel file.
ObjXLApp.Run ("DataSetUp")
' The DataSetUp macro saves the Excel file
' Quit Excel
ObjXLApp.Quit
' Free the memory
Set ObjXLBook = Nothing
Set ObjXLApp = Nothing
End Sub
I have no idea how to fix this! Any help would be much appreciated.
This may be happening because your access database is still open from which the new excel file needs to input data back into. The database cannot be open when this takes place, hense the reason why excel errors and asks for another location to connect to.
So, I would work on generating the needed scrubbing via vba inside access probably.

Excel 2007 workbook locked after access from Access 2007

I've got a project where I'm reading data from an Excel worksheet and saving it in Access tables (not a direct import--see this question if you're interested). My current problem is that any time I run my "import" and then try to open the workbook in Excel, it's "locked for editing" unless/until I close Access. I don't think this should be the case. My process is
Open the workbook with Automation.
Build a collection of sheet names.
Release the Automation objects.
If there's more than one sheet, get user input on which to process.
Open an ADO recordset on a specific range & read some data.
Release the recordset & connection.
Open an ADO recordset on a different specific range & read a bunch o' data.
Release the recordset & connection.
Close the controling form.
Steps 1 - 4 and 9 live in the form file, the remainder in a module.
Am I missing something? I think I've released all the references to the workbook....
If your step #1 includes something like this:
Dim objExcel As New Excel.Application
And later releasing the object is this:
Set objExcel = Nothing
Trying including this line just before you set the object variable to Nothing:
objExcel.Quit
It also helps to make the Excel application instance visible after starting it so you're less likely to leave Excel running unseen:
objExcel.Visible = True

Resources