How to open and activate another workbook in VBA? - vba

I'm creating a macro where I will need to run it in 1 file (called "Masterfile"), it will open and execute the macro on another file ("SurveyReport") and then give me a message box saying "done!".
The code I have to execute on the SurveyReport file works fine when I open that file manually and execute it. The code I need to open SurveyReport from MasterFile is also working it seems, I ran the below with no issues:
Sub PivotTable()
'
' PivotTable Macro
Dim MasterFile As String
MasterFile = ActiveWorkbook.Name
Dim SurveyReport As String
SurveyReport = Application.GetOpenFilename("Excel files (*.xlsx), *xlsx", 1, "Please select the Survey Create Report file", , False)
Workbooks.Open (SurveyReport)
End Sub
But, when I try to activate the SurveyReport file so I can begin executing the macro in it, I get a "Subscript out of range" error. I've tried using the following code after the above block and before the code to execute in the SurveyReport file:
Windows(SurveyReport).Activate
This didn't work, not did:
ThisWorkbook.Activate
...which only had the effect of activating the MasterFile.
SurveyReport file is a .xlsx file. I tried saving it as a .xls file and amending the code, but no joy.
I also tried passing it the file name directly (i.e. Windows("filename.xlsx").Activate), same issue.

ActiveWorkbook is as it says on the tin - whichever workbook happens to be active when the code runs.
ThisWorkbook is always the workbook that the code is sitting in.
You can SET references to specific workbooks rather than just using their names each time. A name can change, or reference the wrong object.... imagine you have a friend called Darren. Each time you mention him you mention him by name. Someone that doesn't know Darren hasn't a clue which Darren out of all the ones available in the world you're talking about. Now imagine you have a little replica of Darren in your pocket... nah, that's a terrible anology - it wouldn't be a replica, it would be a reference to the real Darren... anyway, I digress.
This code sets a reference to the workbook, you can then use that reference any time you want to refer to the correct workbook:
Sub PivotTable()
Dim MasterFile As Workbook
Dim SurveyRptName As String
Dim SurveyReport As Workbook
Set MasterFile = ThisWorkbook '
SurveyRptName = Application.GetOpenFilename("Excel files (*.xlsx), *xlsx", 1, _
"Please select the Survey Create Report file", , False)
If SurveyRptName <> "False" Then
Set SurveyReport = Workbooks.Open(SurveyRptName)
End If
SurveyReport.Activate 'You don't need this line. It doesn't matter if
'the workbook is active, the code knows which one
'you're talking about in the next line.
MsgBox "This is " & SurveyReport.Name & _
" containing " & SurveyReport.Worksheets.Count & " sheets." & vbCr & _
"The value in cell A1 of the first sheet is " & _
SurveyReport.Worksheets(1).Range("A1")
End Sub
Edit: Of course, if you press Cancel when selecting a file then the lines following the IF...THEN code won't have a reference to work on and you'll get a Object Variable or With block variable not set - best not to run the bottom bit of code if you haven't successfully opened the Survey Report file.

The part of the answer that is missing - is that he tried to call a method of an object when his variable was STRING - the open command and subsequent commands will give you an OBJECT - which has properties and methods like .Activate. The STRING type has no such method or property (to be sure - it may have others).
the solution provided by Darren solves this by declaring his SurveyReport as type Workbook - an object of Excel.

Related

VBA Error on opening workbook - Cannot find workbook that is there

I'm attempting to open a workbook, but Excel gives me an error message saying that it cannot find the workbook.
Dim pricing As Workbook
dim fname As String
fname = Dir(ActiveWorkbook.Path & "\Budget Pricing Detail*.csv")
Set pricing = Workbooks.Open(Filename:=fname, UpdateLinks:=False)
As you can see I'm using a wildcard to pull the file name as the last bit of the filename will be different for each instance. What's weird to me as that when Excel gives me the error box it actually names the WHOLE file (even though I never did in my code) I want it to find and says it can't find it. Also what's weird is that this was working already and all of a sudden now it isn't.
I think DIR only returns the filename, and not the entire path. Try:
fname = ActiveWorkbook.Path & "\" & Dir(ActiveWorkbook.Path & "\Budget Pricing Detail*.csv")

Excel VBA macro - Change link name

I have a excel macro routine that I need to prep a file for another routine which is run daily. This prepping involves changes the links of t-1 file to a t0 file.
The code I usually do is:
ActiveWorkbook.ChangeLink Name:= _
"file path", NewName:=new_file_path, Type:=xlExcelLinks
My trouble now is that for this particular routine the file path to be changed to a new routine is not always the same, thus I would need a way to automatize finding out what are the current links to replace them all. The new file path I now because it is the worksheet that is calling this routine and opening this file, so first thing I do Is
new_file_path = "C:\...."& ActiveWorkbook.Name & ".xlsm"
What would help me is if there is a trick to replace all links for a new one, without the need to say the name/path of the old links. Does any one know?
Thanks
To change all the excel links in a workbook try this procedure:
Sub WbThs_ChangeLink_Excel()
Dim wbTrg As Workbook
Dim sLinkNew As String
Dim aLinks As Variant, vLink As Variant
sLinkNew = "##VBA Links Replace - Target 3.xlsb" 'Change as required
Set wbTrg = ThisWorkbook 'Change as required
Rem Set array with all excel links
aLinks = ActiveWorkbook.LinkSources(xlExcelLinks)
Rem Replace each excel Link
If Not IsEmpty(aLinks) Then
For Each vLink In aLinks
wbTrg.ChangeLink Name:=vLink, NewName:=sLinkNew, Type:=xlExcelLinks
Next: End If
End Sub
See the following pages for additional information on the resources used:
Workbook.ChangeLink Method (Excel)
Workbook.LinkSources Method (Excel)
XlLink Enumeration (Excel)

Method 'SaveAs' of object '_Workbook' failed VBA

I have a workbook that is connected to a database and when you refresh the workbook, it refreshes your data in the workbook. Afterwards a macro is ran to save the new (raw) data in two different locations, then the macro will do analysis on that raw data, and save the same workbook later on in 4 other locations.
When I am trying to do the first save of the raw data, I am able to save to the first location, but when it moves to the second location I am getting the error: Run-time error '1004': Method 'SaveAs' of object '_Workbook' failed. Both of the locations are valid locations.
Here is one sub in the macro that does the first file save:
Sub saveraw()
Dim rdate As String
Dim rawfilename As String, rawfilename1 As String
Dim mywb As Workbook
Set mywb = ActiveWorkbook
rdate = Format(Now(), "mm-dd-yy")
rawfilename = "\\sw\mes\PS\SC\SCM_Supply_Execution\Spares\This Weeks Number Database\This Weeks Numbers(raw) " & rdate & ".xlsm"
rawfilename1 = "\\sw\mes\PS\SC\SCM_Shared\Spares Reports\This Weeks Numbers(raw) " & rdate & ".xlsm"
mywb.Save
Worksheets("Sheet2").Range("A2") = Null
Application.DisplayAlerts = False
mywb.SaveAs Filename:=rawfilename
mywb.SaveAs Filename:=rawfilename1
Application.DisplayAlerts = True
End Sub
I have also tried using the method of
ActiveWorkbook.SaveAs
in place of both of the mywb.SaveAs, but that did not work either.
As a test, run the code against file locations only YOU have access to. I'm noticing a reference to shared drive on the second command so maybe someone is already in it and it can't be saved over.
Set display alerts to true for now.
Also, When you run the test macro, make sure you don't have any windows explorer windows open and feed back here with results and I'll assist if it debugs again.
On the face of it, the code looks good to me.
Try this
ActiveWorkbook.SaveAs Filename:="\\sw\mes\PS\SC\SCM_Supply_Execution\Spares\This Weeks Number Database\This Weeks Numbers(raw) " & rdate & ".xlsm" _
, FileFormat:=xlOpenXMLWorkbookMacroEnabled
This might have issues if the file already exists because then a pop-up will ask you if you want to overwrite it or not
Though I think the error is due to an issue with privileges in that specific location or connection issues

1004 Read-Only Error when Opening Closed Workbooks in VBA

To give context to the problem that I'm facing - keep in mind I'm a relative novice - I am attempting to write a code that will open and then close a series of workbooks all contained within a folder, ultimately in order to update a number of VLookups on the master data sheet (since to update them, I believe the dependents need to be open).
Right now, I'm simply attempting to do this for one of the files which I can then go through and do for the rest of the folder. When I do attempt to open the file though, I get the "Run-Time Error 1004" with the message "Excel cannot access 'FolderName'. The document may be read-only or encrypted"
The code I'm using is:
sub openevery_v2()
' openevery_v2 Macro
' Keyboard Shortcut: Ctrl+Shift+O
' Dim diaFolder As FileDialog <-- Ideally the user would use a dialog box to select the folder
' Dim Fname As String
' Dim originalWB As Workbook
' Set originalWB = ThisWorkbook
' originalWB.Save
' Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
' diaFolder.AllowMultiSelect = False
' diaFolder.Show
' Fname = diaFolder.SelectedItems(1)
Fname = "C:\FolderPath"
Openr = Dir(Fname + "Filename.xlsm")
Workbooks.Open (Fname)
End Sub
I've tried to change the settings of the folder from non-read only, but I don't think that is the issue at hand.
Has anyone run through a similar issue or can think of a solution to this particular issue? Alternatively, if there is a better way to think through this challenge, that would be much appreciated.
Your code is trying to open a file named c:\FolderPathFilename.xlsm. Unless that file exists in the root of your C: drive, you'll get errors.
This may be more of what you're after:
Fname = "C:\FolderPath\"
Openr = Dir(Fname & "Filename.xlsm")
Workbooks.Open (Fname)
Notice:
the \ added to the end of Fname.
The + is replaced with a &. VBA uses & for concatenation.
Of course, your code sample does seem to be a very cut-down version of what you're really executing, so that may not be the problem in your real code.

EXCEL VBA: opening XLSM excel using vba

i cant figure out my error in my codes
If cboUnit.Text = "MARINER" Then
Application.ScreenUpdating = False
Application.Workbooks.Open Filename:=ThisWorkbook.Path & "\UNIT" & "\MARINER"
ThisWorkbook.Activate
Workbooks("TOUKEI DATA REPORT GRAPHING").Close
End If
i just want to open xlsm file which is on the folder unit
but i always got an error:
runtime error '1004'
the file this getting is 'xlsx' extension
If you use something like this, it should at least make debugging simpler. Then substitute the code I've provided with this line:
Application.Workbooks.Open Filename:=ThisWorkbook.Path & "\UNIT" & "\MARINER"
Declare the variables with your other variables. I'm understanding your question to be that "Mariner" is the file name. If it's not, you will need to change the fileNPath.
Dim path As String, fileNPath As String
'add these two values above your code
path = ActiveWorkbook.path
fileNPath = path & "\UNIT\MARINER.xlsm"
Application.Workbooks.Open fileName:=fileNPath 'Change this line
Once you've done this, you can see the values for the file path in debug mode where the version you have won't have a value until the line that isn't working anyway. So this way, you can SEE what is going on before you try to USE it.
note: To have a macro enabled workbook, it must be .xlsm, not .xlsx