How to open a Workbook with a password, disable events,
and then copy a sheet in background to the second file and save.
I need in VBA, working in a MS-Access and Excel files
I have done this until now, is working.
Private Sub TestFunction()
'strPath = CurrentDb.Properties(0)
'strPath = Left(strPath, Len(strPath) - Len(Dir(strPath, vbNormal))) & "Temp\"
Dim CopyFrom As Object
Dim CopyTo As Object ''Early binding: Workbook
Dim CopyThis As Object
Dim xl As Object ''Early binding: New Excel.Application
Set xl = CreateObject("Excel.Application")
xl.Visible = True
Set CopyFrom = xl.Workbooks.Open("D:\A01.xls")
'CopyFrom.EnableEvents = False
Set CopyThis = CopyFrom.Sheets(1) ''Sheet number 1
Set CopyTo = xl.Workbooks.Open("D:\PM1.xls")
CopyThis.Copy After:=CopyTo.Sheets(CopyTo.Sheets.Count)
CopyFrom.Close
End Sub
This opens the Excel, I enter the pass copy's the sheet to second File.
But I need to pass the password in background, delete the sheet and save the second file, all in background.
Also I need to delete a sheet, without asking me, like :
CopyTo.Sheets("Sheet1").Delete
Thank you
Password issue
Be careful to check wether it is an "open file" password (password parameter) or a "modify file" password (WriteResPassword parameter).
Something like:
Sub OpenMyFile()
Workbooks.Open Filename:="Path", Password:="OpenFile", WriteResPassword:="WriteFile"
End Sub
Delete without alert
For your second question, here is what you can do:
Application.DisplayAlerts=False
CopyTo.Sheets("Sheet1").Delete
Application.DisplayAlerts=True
Related
I have appended a code I tested to copy and paste some data to Excel. i want to do 1) Check if directory exists 2) if it doesn't create it 3) if it does, display message box and stop the sub
Dim excelapp As Excel.Application
Dim wbTarget As Excel.Workbook
Dim qdfquerytest As QueryDef
Dim rsquerytest As Recordset
Set qdfquerytest = CurrentDb.QueryDefs("OpenComplaintsQuery") 'which query to define
Set rsquerytest = qdfquerytest.OpenRecordset() 'which recordset to open
Set excelapp = CreateObject("Excel.Application") 'create an Excel instance
excelapp.Visible = True 'Make Excel visible
If Len(Dir("O:\1_All Customers\Current Complaints\Complaint Folders\" &
rsquerytest(1).Value)) = 0 Then
MkDir "O:\1_All Customers\Current Complaints\Complaint Folders\ &
rsquerytest(1).Value"
Else
MsgBox "Folder already exists!", vbOKOnly
Exit Sub
End If
When i run i get runtime 75 error about file path isn't valid. I am pretty sure if the way i have the directory typed out to include rsquerytest(1) which is a serial number in the record. Additionally despite the error the code continues to run should i have put the If statement BEFORE setting Excel app?
Editting Post to post Code that is working
Private Sub cmdcopyfieldsonly_Click()
'This function works
'Things to add Checking for directory usage, Create the
directory, Stopping if directory is found and msg box,
'Declare and set excel objects and target data
Dim excelapp As Excel.Application
Dim wbTarget As Excel.Workbook
Dim qimsnum As Variant
Dim rsquerytest As Recordset
Set rsquerytest =
CurrentDb().OpenRecordset("OpenComplaintsQuery") 'which
recordset to open
Set qimsnum = Me.[QIMS#]
Dim savepath As String
Dim openpath As String
savepath = "Redacted filepath"
openpath = "Redacted Filepath"
'Set excelapp = CreateObject("Excel.Application") 'create an
Excel instance
'excelapp.Visible = True 'Make Excel visible
If Len(Dir(savepath & Me.[QIMS#], vbDirectory)) = 0 Then
MkDir savepath & Me.[QIMS#]
Else
MsgBox "Folder already exists!", vbOKOnly
Exit Sub
End If
I did leave portions after the If out as it does not pertain to this issue, June7 should have listened to you the first time i believe in a previous post you helped me with, I couldn't wrap my brain around it. and i am well aware this code can be cleaned up further ;), i am just working out the basic functions and will clean it up from there. Thank you for you support!
I want to update a read-only workbook from the file "Data.xlsx".
I change the file in another application in a read-write workbook.
When I try to close the read-only workbook after updating it, an error accours.
This is my code:
Option Explicit
Public xlApp As New Application
Public wb_readWrite As Workbook
Public wb_readOnly As Workbook
Sub main()
Dim path As String
path = ThisWorkbook.path & "\Data.xlsx"
Set wb_readOnly = Workbooks.Open(path, readOnly:=True)
Set wb_readWrite = xlApp.Workbooks.Open(path, readOnly:=False)
wb_readWrite.Sheets(1).Cells(1, 1) = InputBox("Input your data")
wb_readWrite.Save
MsgBox "Update Now"
wb_readOnly.UpdateFromFile
wb_readWrite.Close
wb_readOnly.Close 'Error is here
Set wb_readWrite = Nothing
Set wb_readOnly = Nothing
End Sub
Looks like calling UpdateFromFile reloads the workbook and breaks any existing VBA references to the workbook - you need to re-establish any references after the update.
So you could use a wrapper like this for example:
Sub ReloadWorkbook(wb As Workbook)
Dim app As Application, nm As String
Set app = wb.Application 'in case in a different instance of Excel
nm = wb.Name
wb.UpdateFromFile
Set wb = app.Workbooks(nm)
End Sub
and call
ReloadWorkbook wb_readOnly
instead of wb_readOnly.UpdateFromFile
I have some code for exporting subform results to Excel workbook. Code works fine, only one small issue. If I do export, excel file opens If user wants I open. When this Excel file is opened and user wants to do Export again, I receive error 1004.
This error is produced because file is open, and new Excel object want to save a file with same name. What I want is when this happens, just cancel everything and let user know that he must first close this previously created workbook. Here is what I tried:
If Err.Number = 1004 Then
MsgBox "Error. You have opened Excel file, that has same name as this file name should be. Please close that file first !", vbCritical
Cancel = True
Set wb = Nothing ' wb is wb=XcelFile.Workbooks.Add
Set XcelFile = Nothing ' Xcelfile is Xcelfile= New Excel.Application
End If
This code works, when user closes that file, export can be performed - old file is just overwritted. Problem is that Excel application is still opened in Windows Task Manager, so Excel object is not properly closed.
Does anybody have a better solution ?
P.S.: I tried including numbers in file name of Excel, so that It wouldn't be same name, but I can't get It fixed.
EDIT: Here is how I tried changing filename
Dim i as Integer
ExcelFilename = "RESULTS_" & Format(Date, "dd/mm/yyyy") & "_" & i & "_" & ".xlsx"
i = i + 1
"i" doesn't change It's value when I run code once again. How can I make it increment ? This would solve my problem...
I suggest a simple solution: add the time to the file name to prevent conflicts.
ExcelFilename = "RESULTS_" & Format(Now(), "yyyy-mm-dd_hh-nn-ss") & ".xlsx"
For a number that will increment as long as the application is running, try
Static i As Integer
Static variables
You must be very strict in opening the Excel objects and closing them in reverse order - as done in this example:
Public Sub RenameWorkSheet()
Dim xls As Excel.Application
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Set xls = New Excel.Application
Set wkb = xls.Workbooks.Open("c:\test\workbook1.xlsx")
Set wks = wkb.Worksheets(1)
wks.Name = "My New Name"
wkb.Close True
Set wks = Nothing
Set wkb = Nothing
xls.Quit
Set xls = Nothing
End Sub
I have some code for exporting subform results to Excel workbook. Code works fine, only one small issue. If I do export, excel file opens If user wants I open. When this Excel file is opened and user wants to do Export again, I receive error 1004.
This error is produced because file is open, and new Excel object want to save a file with same name. What I want is when this happens, just cancel everything and let user know that he must first close this previously created workbook. Here is what I tried:
If Err.Number = 1004 Then
MsgBox "Error. You have opened Excel file, that has same name as this file name should be. Please close that file first !", vbCritical
Cancel = True
Set wb = Nothing ' wb is wb=XcelFile.Workbooks.Add
Set XcelFile = Nothing ' Xcelfile is Xcelfile= New Excel.Application
End If
This code works, when user closes that file, export can be performed - old file is just overwritted. Problem is that Excel application is still opened in Windows Task Manager, so Excel object is not properly closed.
Does anybody have a better solution ?
P.S.: I tried including numbers in file name of Excel, so that It wouldn't be same name, but I can't get It fixed.
EDIT: Here is how I tried changing filename
Dim i as Integer
ExcelFilename = "RESULTS_" & Format(Date, "dd/mm/yyyy") & "_" & i & "_" & ".xlsx"
i = i + 1
"i" doesn't change It's value when I run code once again. How can I make it increment ? This would solve my problem...
I suggest a simple solution: add the time to the file name to prevent conflicts.
ExcelFilename = "RESULTS_" & Format(Now(), "yyyy-mm-dd_hh-nn-ss") & ".xlsx"
For a number that will increment as long as the application is running, try
Static i As Integer
Static variables
You must be very strict in opening the Excel objects and closing them in reverse order - as done in this example:
Public Sub RenameWorkSheet()
Dim xls As Excel.Application
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Set xls = New Excel.Application
Set wkb = xls.Workbooks.Open("c:\test\workbook1.xlsx")
Set wks = wkb.Worksheets(1)
wks.Name = "My New Name"
wkb.Close True
Set wks = Nothing
Set wkb = Nothing
xls.Quit
Set xls = Nothing
End Sub
Good Morning All,
I have fought with this for a few days now, and have not yet found a suitable solution, so I hope somebody can put me out of my misery!
From within an excel document, I have 3 buttons to check out and open 3 documents from a Microsoft Sharepoint Server. 2 files are Excel workbooks, and one is a Word document.
The excel files work absolutely fine, but the Word document always returns 'False' when the .CanCheckOut statement is reached, even though I can manually check it out on MOSS, have the correct permissions etc. I have added the Microsoft Word 11.0 Object Library reference in my Excel VBA.
Here is my code for the excel ones:
Sub CheckOutXL(FullPath As String)
Dim xlApp As Object
Dim wb As Workbook
Dim xlFile As String
xlFile = FullPath
Set xlApp = CreateObject("Excel.Application")
'Determine if workbook can be checked out.
If Workbooks.CanCheckOut(xlFile) = True Then
'Check out file
Workbooks.CheckOut xlFile
'Open File
Set xlApp = New Excel.Application
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(xlFile, , False)
'Otherwise offer the option to open read-only
Else
If (MsgBox("You are unable to check out this document at this time, would you like to open it read-only?", vbYesNo) = vbYes) Then
Set xlApp = New Excel.Application
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(xlFile, , False)
End If
End If
and for the Word one:
Sub CheckOutDoc(FullPath As String)
If Documents(docFile).CanCheckOut = True Then 'This is the one that returns FALSE
Documents.CheckOut docFile
' Set objWord = CreateObject("Word.Application") 'The commented out section was
' objWord.Visible = True 'a second way I tried to open
' objWord.Documents.Open docFile 'the file.
Documents.Open Filename:=docFile
Else
If (MsgBox("You are unable to check out this document at this time, would you like to open it read-only?", vbYesNo) = vbYes) Then
Documents.Open Filename:=docFile
End If
End If
End Sub
These are both called using a simple line for each button as such:
Private Sub btnTrend_Click()
Call CheckOutXL("FullPathOfTheFileInHere.xls")
End Sub
Any help massively appreciated!! Thanks
We are having the same issue. Can you try this:
If CBool(Documents(docFile).CanCheckOut) = True Then