Activate Workbook WITHOUT filename but using the extension - excel

I have slowly learning some VBA by searching them through google, this site has the best format for understanding the answers. I have been able to really automate many of my reports but have hit a wall in searching out this function.
I have a many reports and we use a web interface to generate specific data. the file names are always randomly generated when exported, but they are always (read only) .xls files.
I have tried other VBA commands that i have searched heavily but none work. using the "*.xls" doesnt seem to work. these have no file path, but are the only .xls workbook open when running this report.
I would appreciate any assistance.

Welcome to SO.
In your question you say have no file path, but are the only .xls workbook open when running this report.
If this is true (the .xls workbook you want is the ONLY one opened at this time), then this code may work for you.
It will loop trough each opened workbook and check the extension of the file. If it is XLS then it will activate it.
Dim f As FileSystemObject
Set f = New FileSystemObject
Dim WB As Workbook
For Each WB In Application.Workbooks
If f.GetExtensionName(WB.FullName) = "xls" Then
WB.Activate
'rest of your code
End If
Next WB
Set f = Nothing
To make this code work, you need to activate a reference:
In the VBA Editor, go to TOOLS-> REFERENCES and search for Microsoft Scripting Runtime
Hope this can help you

Related

Excel Workbooks that I open in VBA still appear in the project explorer after closing them and setting the Workbook to Nothing

I want to open an Excel file to read some values from it and then close it again. I use the following, simplified code for it.
Dim wbImportFile As Workbook
Dim sFilePath As String
sFilePath = "C:\...\Kundenstamm...xlsx"
'open the workbook read only
Set wbImportFile = Workbooks.Open(sFilePath, ReadOnly:=True)
'Read some values from the open Excel file - nothing very complicated happening here
'...........
'...........
'Close file
wbImportFile.Close False
Set wbImportFile = Nothing
However, after closing the file, it still shows up in the project explorer and each time I run the macro, one more project is added to the project explorer:
I found several similar questions on Stackoverflow, like this one, where Set Workbook = Nothing did the trick, but I am doing that one already.
The accepted answer in this question did not help me either (specifying SaveAs:=False).
I have to add that the problem only occures when the VBE is open. If I do not have the code editor open and run the code, no additional projects will appear. However, closing and opening the VBE does not remove the unwanted projects from the project explorer.
Since these projects do not appear when the VBE is closed, I am wondering if this is actually a problem? And if so, what am I doing wrong and can I fix it?

How to deal with co-authoring while editing an Excel file in Sharepoint via VBA

I have an excel file stored in Sharepoint (which is also accessible with Microsoft Teams), with the path: https://organization.sharepoint.com/PathOfFile/myFile.xlsx
The file can be edited by multiple at the same time with the co-authoring feature in Sharepoint.
I want to use another excel file stored locally in my computer to access and modify the one in Sharepoint. This local file has a button with this VBA code in it:
Sub UpdateSP():
f_name = "https://organization.sharepoint.com/PathOfFile/myFile.xlsx"
Workbooks.Open f_name
Workbooks("myFile.xlsx").Activate
ActiveWorkbook.Sheets("sheet1").Activate
Range("A" & Rows.Count).End(xlUp).Offset(1).Select
ActiveCell.Value = 9999
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = 0000
ActiveWorkbook.Close SaveChanges:=True
End Sub
In principle it works, the file in Sharepoint is modified. But things go wrong if there's someone editing the file while I run the code, then two versions of the file seem to be created, one for the online-live editing, and the one for my code.
If this happens, the online version of the file won't show the changes made by the code, and whenever the file is opened with the excel app, a pop-up will show asking which version of the file should be kept, losing all the changes done in the disposed version.
I have tried to use the CanCheckOut and CheckOut methods, but CanCheckOut always returns False for whatever reason (there are some questions here with the same issue but I havent been able to find a solution).
Can someone suggest a solution to this issue? Thanks.
I'm not 100% sure it will work on SharePoint, but in theory, ADODB is a library for VBA that has the syntax of objects to use Microsoft's Jet Engine so you can open files AdLockOptimistic---ally. ((look up lock types in ADO.net))
This works on a file directory basis, so if the DB being modified is open, it will handle the update.
Instead of using Excel's Application to open the file, you would establish an ADO connection, and then specify the type of Lock in order to access the Excel's sheets and tables inside it.
This works for shared / network drives, so I'm guessing since SharePoint can be mapped as a file explorer drive, then ADO should work and is worth a try.
Here's a basic example to get you started: ADO question
Try enabling the autosave after activating the workbook.
To do so, add this line:
ActiveWorkbook.AutoSaveOn = True
after the Workbooks("myFile.xlsx").Activate line.
I have had similar issues with collaborative files and making sure the autosave is enabled has solved it.
To be able to incorporate changes that way your code must run inside a coauthoring context.
Instead of opening the document from another doc or local copy, the code must be running inside the same document being opened from the same source URL (Sharepoint or OneDrive), that way the add-in or macro can make changes that Excel itself will handle on a coauthoring context.
I recommend taking a look at Coauthoring in Excel add-ins of the Office Dev Center, including the linked articles inside (specifically "coauthoring", redirecting to the support center, and "About coauthoring in Excel (VBA)" at the bottom with more samples).
CanCheckOut will always return false if a workbook is open. Thus you must check before you touch it. The CheckOut command will not open the file so we must also have an open statement after CheckOut.
Using your example it would look like this;
Option Explicit
Public Sub UpdateSP()
Dim fName As String
fName = "https://organization.sharepoint.com/PathOfFile/myFile.xlsx"
If Workbooks.CanCheckOut(fName) Then
Workbooks.CheckOut fName
Dim myFile As Workbook
Set myFile = Workbooks.Open(fName)
Dim mySheet As Worksheet
Set mySheet = myFile.Sheets("Sheet1")
Dim startRange As Range
Set startRange = mySheet.Range("A" & mySheet.Rows.Count).End(xlUp).Offset(1)
startRange.Value = 9999
startRange.Offset(0, 1).Value = 0
myFile.Close SaveChanges:=True
Else
MsgBox fName & " can't be checked out at this time.", vbInformation
End If
End Sub

Copy and Paste between different Excel instances

I bought a software (with a large database), and its output is a simple Excel workbook, not saved anywhere (no path), named generically "Book1", that simply pops up on my screen.
Every time I ask the software for this output, I need to copy the content of this workbook and paste into another workbook, a mother-workbook, as I named it, to consolidate all the data.
I have to repeat this action dozens of times a day, so I thought it would be a great idea to create some VBA code to automate this task.
So... I made a very simple one:
ActiveWorkbook.ActiveSheet.Range("A1:C32").Copy
Workbooks("Mother-Workbook.xlsm").Worksheets("Sheet1").Range("B6:D37").PasteSpecial Paste:=xlPasteValues
The problem is... Each time the software outputs a new workbook, it seems that it is created in a new instance of Excel, which my macro can't reach. I mean, I run the code, but nothing happens, because my mother-workbook doesn't find the generic, unsaved and located in another excel instance "Book1".
If I open the mother-workbook after the output is opened, OK, the code works, because both are in the same instance. But as I need to keep the mother-workbook open all the time, I can't do this. I don't want to save each new output file either. It would take me a lot of time.
I'm using the 2016 version of Excel, but already tried the 2010 as well. My OS is Windows 10 Pro.
Any thoughts?
This code should do it.
Dim xlapp As Object
Set xlapp = GetObject("Book1").Application
xlapp.ActiveWorkbook.ActiveSheet.Range("A1:C32").Copy
Workbooks("Mother-Workbook.xlsm").Worksheets("Sheet1").Range("B6:D37").PasteSpecial Paste:=xlPasteValues
xlapp.DisplayAlerts = False
xlapp.Quit
Note that you need to close "Book1" at the end of your code to make sure that the next time an Excel file is created it will also be called "Book1" and not "Book2". And might as well close the Excel instance while we are at it!
For more information on the GetObject function, you can have a look at this page
Thanks a lot, DecimalTurn and Patrick Lepelletier!
The GetObject really helped me. The "closing" command worked better like this:
Sub CollectA()
Dim oApp As Application
Dim oWb As Workbook
Set oWb = GetObject("Book1")
Set oApp = oWb.Parent
oWb.ActiveSheet.Range("A1:C32").Copy
Workbooks("Mother-Workbook.xlsm").Worksheets("Sheet1").Range("B6:D37").PasteSpecial Paste:=xlPasteValues
oWb.Close False
oApp.Quit
End Sub
Cheers!

How can I refer to another workbook by the content of a cell in the current workbook?

I'm making a macro in excel 2010 and my goal is that everyone can use this macro for their own work. Therefore I have to make it very flexible.
Everyone names their own workbook (I've solved this in the macro by using ThisWorkbook), but everyone also names their own extraction file (from where the new data comes).
However, almost no-one knows how to work with VBA so it's not possible to adjust this reference in the code every time.
Therefore, I've added a new sheet: 'Personalize'
In here, the person can add the name of the extraction file in a specific cell.
Unfortunately I don't know how to open a workbook that has the name of a specific cell in the current workbook.
I tried, for example, Windows("ThisWorkbook.Sheets("Personalize").Range("B3")").Activate but it didn't work.
The same thing with sheets that can be named differently, I don't know how to adjust them in the macro without using VBA in every case.
Does anyone have any ideas or suggestions?
Thank you so much in advance!
Kind Regards,
Hendrik
If you want to open a workbook that's closed you need the full path:
dim wkb as workbook
dim wbPath as String
wbPath = ThisWorkbook.Sheets("Personalize").Range("B3").value
Set wkb = Workbooks.Open(wbPath )
If you want to activate a workbook that's already opened, you don't need the full path but the workbook's name (such as "Workbook1.xlsx"). For this you can shave off the path before reaching "Workbook1.xlsx" (alternatively if the workbook is always going to be opened first, just have them enter the workbook's name directly and skip taking out the rest of the path):
dim wbname as String
wbname = ThisWorkbook.Sheets("Personalize").Range("B3").value
Do until Instr(wbname, "\") = 0
wbname = Mid(wbname, instr(wbname, "\") + 1) 'I didn't test this, just going off the top of my head
Loop
Workbooks(wbName).Activate
Be sure to handle your errors properly. For reference: VBA Excel simple Error Handling
Test what happens when you try to input a name that's incorrect, for example. You want to handle those errors with appropriate messageboxes or the users may feel like your program doesn't work.

Using VBS to open text file in excel and run macro without opening excel

This might sound confusing, and I'm not entirely sure it's possible to do it the way I want, but what I'm looking to do is create a script that will take a .txt file and run Excel macros on it, without actually opening up Excel or the file. One of the blogs I was reading suggested this method, but I'm not very familiar with VBS.
Set objExcel = CreateObject("Excel.Application")
objExcel.Application.Run "'Path\Test.xlsm'!Module.Macro"
objExcel.DisplayAlerts = False
objExcel.Application.Quit
Set objExcel = Nothing
This did not work when I tried to use it with a .txt file.
The error I receive is Cannot run the macro Path.... The macro may not be available in this workbook or all macros may be disabled
I'm sure it has something to do with my lack of VBS knowledge, but so far it's been the closest kind of script I've found for what I'm looking for. Is what I'm trying to do possible?
You need to open the workbook before you can run macros from it.
...
Set wb = objExcel.Workbooks.Open("C:\path\to\Test.xlsm")
objExcel.Application.Run "'Path\Test.xlsm'!Module.Macro"
...
You can't run a macro without opening Excel or the file containing the macro. If you want something like that you need to translate the VBA code to plain VBScript.
Path statement need full path eg " c:\ .... "
And I think it should be Module1.Macro_Name (not Module)
Write in note pad but save with .vbs on desktop. Just click on the run

Resources