Switching between different workbooks without using .activate - excel

I want to reference different workbooks in my code and I have used this code:
Dim Basicwb As Excel.Workbook
Dim Basic As Excel.Application
Set Basic = New Excel.Application
Set Basicwb = Basic.Workbooks.Open("X:\Job\Masroori\3-042-PMS.xlsx")
but the problem is how can I refrence it if I dont want to open it each time. I used this code (without .Open) but I get this Error! : "Subscript out of range"
Set Basicwb = Basic.Workbooks("X:\Job\Masroori\3-042-PMS.xlsx")
Also, I dont want to activate the workbook each time, Is there any way?

Taken from the msdn site for the Workbooks property:
"Returns a Workbooks collection that represents all the open workbooks. Read-only."
hence the last line of your code gives you an error since the file is not open. AFAIK, you cannot reference objects within a workbook if that workbook is not open. You can access whatever a workbook has without activating it (so without using .Activate), but it has to be open. Maybe this SO question is of help to you:
Open Excel file for reading with VBA without display
If your workbook is open, you can do the following:
Dim wBook as Excel.Workbook, rngTemp as range
Set wBook = workbooks("wbName.xls")
With wBook
' Do stuff, no need to activate. Example:
set rngTemp=.sheets(1).usedRange
End With
I hope this helps?

Related

Workbooks added by Workbook.Add command is not visible in task bar

I am facing a very weird problem wherein, I am creating a new workbook using the below code, but the new workbook thus created, is not visible and it is not even showing up in the taskbar.
The code lies in a powerpoint file.
Dim wb As Workbook
Set wb = Excel.Workbooks.Add
Application.Visible = msoTrue ' Forcing this also doesn't solve
The same issue is happening with the code of opening an excel with the following code
Dim MyWorkbook As Workbook
Set MyWorkbook = Workbooks.Open(fullpath) ' full path is the path to existing excel file
Application.Visible = True ' Forcing this also doesn't solve
I can't figure out why this is happening. Any help is much much appreciated. Here is what I have tried
Made sure the excel library references is added.
Used the Application.Visible = True in code
Have even restarted the system multiple times.
Tried to set Excel -> Options -> Advanced -> Show All Windows in the Taskbar check box, as suggested in forums, but didn't find this option in excel though.

Error when opening excel file for certain user - 'The remote procedure call failed..."

I have a windows application written in vb.NET that pulls details from a big excel workbook and uses them to create site specific documents, depending on what site a user of the application has been assigned. The application then opens up the excel workbook it creates, and populates certain cells with the desired information, before opening a word document it has created to do similar.
The application was working perfectly for all users, but has recently stopped working for a user with Windows 8.1 and 32-bit Excel 2013. The application opens up the master excel workbook and pulls all necessary information from it, however when it tries to open the excel workbook it has created, it cannot proceed any further and eventually throws the following error:
The remote procedure call failed. (Exception from HRESULT: 0X800706BE).
The following is the code that opens up the master workbook, closes it, then copies the workbook template, renames it and finally opens it.
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Dim excelApp As Excel.Application = Nothing
Dim excelWB As Excel.Workbook = Nothing
Dim excelWS As Excel.Worksheet = Nothing
Dim fso As Scripting.FileSystemObject
Dim MasterLogLoc As String 'Path to the master workbook is stored in this string
Dim SiteTempLoc As String 'Path to the workbook template
Dim SiteWbLoc As String 'Path to the newly created wb
excelApp = New Excel.Application
excelWB = excelApp.Workbooks.Open(Filename:=MasterLogLoc, [ReadOnly]:=True, UpdateLinks:=False)
excelApp.Visible = False
excelWS = excelWB.Worksheets("Master")
excelWS.Select()
'Whatever details that are needed are grabbed
excelWB.Close(SaveChanges:=False)
excelApp.Quit()
excelApp = Nothing
excelWB = Nothing
'Next the template is copied and the newly created workbook is opened
fso = New Scripting.FileSystemObject
fso.CopyFile(Source:=SiteTempLoc, Destination:=SiteWbLoc)
fso = Nothing
'The application times out at the next part
excelApp = New Excel.Application
excelWB = excelApp.Workbooks.Open(SiteWbLoc)
excelApp.Visible = False
'The application times out at the above part
'Whatever needs to be done to the worksheet is completed
excelWB.Save()
excelWB.Close()
excelApp.Quit()
End Class
My computer is Windows 7, with Excel 2010 64-bit, and the application still works perfectly, it also still works perfectly on another Windows 7 computer.
The first time the user got this error, I got them to manually open up the workbook template, which showed that they did not have the file as a trusted document for their PC. After fixing this, they ran the application successfully but the next day the error appeared again, even though the workbook was now a trusted document.
The fact that the application opens up an already existing workbook successfully, but cannot open the workbook created on that PC, appears to be the main sign of the problem, however I am unsure where to proceed to next for troubleshooting this.
Could late-binding work? Or have I something missing from my code that makes the application more robust when operating on different versions of windows and excel?
I tried a late binding solution, however that didn't solve the problem, but I did manage to find a solution.
The excel worksheet the application copied had links to other excel worksheets - the links were outdated and not functioning correctly, which meant that every time the newly created worksheet was opened, a user had to select 'Enable Content' - not sure how I missed this!
I solved this problem by:
1) Fixing the links on the worksheet template being copied
2) Making the network drives, which held both the worksheet template and also the worksheets that the template had links to, trusted locations.

Transfer open workbook from one Excel instance to another

Is it possible to transfer an open workbook to another Excel instance? I.e. 're-parenting' an open workbook without closing and re-opening?
The reason I want to do this is to have a separate instance for a particular workbook. When that workbook opens, it can create a new instance of Excel, and then I'm hoping to somehow add that workbook to the other applications Workbooks collection, while removing it from the original.
The point of this is so that I can run a modal forms application, while still retaining the ability to use Excel. For example, I'd like to programatically copy data to the clipboard while letting the user paste it into another workbook.
Making the original forms application non-modal is NOT a solution as this is a requirement (we've gone to elaborate lengths to keep regular users out of the worksheets and only close the forms with a password.)
For context, I've tried opening the other instance with the same workbook and then closing, but this has problems with the newly opened workbook being read-only. (There are also other reasons why this doesn't work well.)
As the code below demonstrates, you can access a workbook in another instance of Excel and manipulate it.
Dim xlApp As Excel.Application
Dim Wb As Workbook
Dim xlApp2 As Excel.Application
Dim Wb2 As Workbook
Set Wb = ActiveWorkbook
Set xlApp = Wb.Parent
Set xlApp2 = New Excel.Application
Set Wb2 = xlApp2.Workbooks.Open("E:\My Documents\Weekly Report.xlsx")
Wb.Worksheets("Target").Cells(1, 1).Value = Wb2.Worksheets(1).Cells(4, 1).Value

Excel Macro Stored in Access

So I'm importing data every day into Access to use for reporting. The data comes from several spreadsheets created by different individuals. Because those individuals like to format things incorrectly I created a macro that reformats their document so that it can be imported cleanly into Access for me to use. Works great but it gets tedious having to open up each Excel sheet to run this Macro.
What I'm trying to do is place the Excel Macro in Access and then run the formatting code before importing it all at once. I am a bit lost in approaching this. I'm aware of ways to run Macros already placed in Excel sheets but is there a way to run a macro that is stored in Access that works in excel. I also thought to maybe inject the Macro into the excel document and then run it.
To sum things up, what I'm hoping to do is from Access, store a macro, that can be used to alter Excel Files.
Is this at all possible? If so How? Is there another approach?
What you are asking to do is automate Excel from Access. Yes, you can do this. In Access, add a module, add a reference to the Microsoft Excel object model (Tools: References), and use this framework code to get you started:
Sub PrepExcelFileForImport()
Dim xl As Excel.Application
Dim wbk As Excel.Workbook
Dim wst As Excel.Worksheet
Set xl = CreateObject("Excel.Application")
With xl
.Visible = True
Set wbk = .Workbooks.Open("c:\temp\temp.xlsx")
Set wst = wbk.Worksheets("data")
With wst
' add your formatting code here, be sure to use qualified references, e.g.
.Rows(1).Font.Bold = True
End With
End With
wbk.Close SaveChanges:=True
xl.Quit
End Sub

VBA Excel 2003 Macro independent from specific Workbook

Okay, so I've written a Macro that works fine when launched from the Workbook which I coded it in. However, I need the Macro to be able to work across various Workbooks.
I've moved the Macro to the hidden "personal" workbook, but, now when the code references "ThisWorkBook", well, yeah, it points to the personal workbook.
I had thought of just creating a workbook variable and pointing to the address/name of the workbook... but this varies (the workbook is generated by a system, and the name of the workbook is dependant on the time/date generated).
For reference, I want to put a button on the toolbar in Excel, and when the user clicks it, it runs this Macro. Is there, perhaps, a way to get the name of the Workbook that calls the Macro?
Thanks,
Sam.
There are Active commands which will allow you to reference the workbook and worksheet that the code is been called from.
ActiveCell
ActiveChart
ActiveEncryptionSession
ActivePrinter
ActiveProtectedViewWindow
ActiveSheet
ActiveWindow
ActiveWorkbook
All properties of the Application object
If there's a naming convention in workbook A (the data workbook) , you can do the following changes
to identify workbook A
Dim wbA As Workbook 'workbook A ( the data workbook)
Dim wb As Workbook
For Each wb In Workbooks 'loop through all opened workbooks, matching the name
If InStr(wb.Name, "ABC") > 0 Then
Set wbA = wb
Exit For
End If
Next wb
then replace the "ThisWorkBook" by wbA
You could also use VBS instead of a macro. The languages are pretty much identical, and your script would be independent of your workbooks.
As far as identifying which file to use to run the macro (without examples of your data and code, it's hard to be too specific), you can browse for the file you want.
Dim objShell
Set objShell = CreateObject("Shell.Application")
Dim strFileName
Dim strFilePath
Dim dPicker
Set dPicker = objShell.BrowseForFolder(0, "Choose a file:", &H4000)
strFilePath = dPicker.self.Path 'will give you the file path of the file you choose,
'which you can then use to open/access the file with
'the data you need.
'Code
Set dPicker = Nothing
If you want to stick with a macro, you can check out the FileDialog Object for using the file picker in VBA.
To get the filename and/or path of an open workbook in VBA, use
ActiveWorkbook.Name
ActiveWorkbook.Path
Hope this helps!
Just replace "ThisWorkbook" by "ActiveWorkbook".

Resources