Userform to navigate and select another open workbook - vba

I have a small program VBA which is fact a userform which allow me to display all the existing worksheet of one open workbook on which I am working. Via this userform I can select another sheet and by clicking the sheet via this userform, it reorients me to the desired worksheet.
Now I tried to modifiy a bit of part of this program in order to do it the same but with all my open workbooks. It means if I have several workbook open, I would like that my userform allows me to display all the existing open workbook and by selecting the desired workbook via the userform, it reorients me to this workbook (it means that the selected workbook in the userform is activated and selected). The problem is when I run the code, I have an error message 424 VBA Run-time error '424' Object Required Error…
PS:really sorry for the format of my Code but I do not manage to put it in the right format..
Thanks in advance for your help
Xavi
Here please find the original code which works for userform related to worksheet (this one works):
Sub UserForm_Initialize()
Dim n As Long
Dim msg As String
Dim i As Long
Dim s As String
Dim sht As Worksheet
Do
n = n + 1
Me.ListBox1.AddItem Sheets(n).Name
Loop Until n = Worksheets.Count
End Sub
Here please find the modified code for userform related to workbook (this one does not works: run time error 424):
Sub UserForm_Initialize()
Dim n As Long
Dim msg As String
Dim i As Long
Dim s As String
Dim Wb As Workbook
Do
n = n + 1
Me.ListBox1.AddItem Workbooks(n).Name
Loop Until n = Worksbooks.Count
End Sub

If there is no reason for the actual number to be parsed in your code, then why not just loop the sheets directly?
Sub UserForm_Initialize()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
Me.ListBox1.AddItem ws.Name
Next ws
End Sub

May I propose a simple for loop ?
Dim i As Long
For i = 1 To Application.Workbooks.Count
Debug.Print Application.Workbooks(i).Name
Next
Then, if you have different instances of Excel (different Application objects then the one your Userform came from), this become a little bit more complex. (This is probably not the case if you are working in Excel 2010 or newer). But, if this is the case, it requires a couple of Win32 API calls and some insights on the "windows" of Excel. I've found my answers here in the past : Can VBA Reach Across Instances of Excel?

Related

Open a closed workbook to a specific sheet based of a cell value

I've spent to much time trying to figure this out and would appreciate some help.
I would like to open a closed workbook based off a cell value (eg A1) containing a file path and have it open up to the sheet matching another cell (eg A2).
for example A1 = C:\User\TEST.xls
and A2= Sheet3
I would like a button that opens C:\User[TEST.xls]Sheet3
Here's what I've got so far:
Sub OpenSesame()
Dim ClosedBook As Workbook
Set ClosedBook = Workbooks.Open(Filename:=Application.Range("ClosedBookFile").Value)
'ClosedBookFile is a named cell
ClosedBook.Sheets(*DYNAMIC CELL VALUE*).Activate
Range("A1").Select
End Sub
What can I put instead of dynamic cell value to open to a specific sheet or am I barking up the wrong tree?
Thanks for your help
Probably it is a good idea to refer the Name of the worksheet as a variable and refer it later. Something like this:
Option Explicit
Sub OpenSesame()
Dim ClosedBook As Workbook
Dim nameOfWorksheet As String
Dim pathToOpen As String
With Worksheets(1)
nameOfWorksheet = .Range("A10") 'for example
pathToOpen = .Range("ClosedBookFile")
End With
Set ClosedBook = Workbooks.Open(pathToOpen)
ClosedBook.Worksheets(nameOfWorksheet).Activate
Range("A1").Select
End Sub
Furthermore, it is a good practice to refer the worksheet, whenever you are referring to a range. Thus, With Worksheets(1) refers the first worksheet in your current workbook.
Along #Vityata lines, I'd add you need explict reference of which workbook the worksheet with data belongs to, and avoid implicit reference to the currently active workbook
here's a compressed code with what above
Option Explicit
Sub OpenSesame()
With ThisWorkbook.Worksheets("myWorksheetWithFileInfoName") ' reference worksheet holding info of workbook and worksheet to activate
Workbooks.Open(Filename:=.Range("ClosedBookFile").value).Worksheets(.Range("A2").value).Activate ' open wanted workbook and activate wanted worksheet
'from now on the wanted worksheet in the wanted workbook is the active one
Range("A1").Select ' almost always not needed
End With
End Sub

Copy / paste same range of cells of many sheets from one book to another

I'm rather new to VBA and I'm trying hard to solve the following problem. I usually get an excel file with 10-20 sheets. Then, I copy the same range of cells (i76:i133) of every sheet from one book to another book that has the same sheet structure.
I'm trying to make a loop to code this easily but I'm failing.
Sub copy()
Dim Sourcebook As Workbook
Dim Destinationbook As Workbook, mysheet As Worksheet
Set Sourcebook = Workbooks("Quarterly.xlsx")
Set Destinationbook = Workbooks("Master.xlsx")
For Each mysheet In Sourcebook.Worksheets
Sourcebook.Sheets(mysheet).Range("I76:I133").Copy
Destinationbook.Sheets(mysheet).Range("I76").Paste
Next
End Sub
I get a
run-time error 13, type mismatch
in Sourcebook.Sheets(mysheet).Range("I76:I133").Copy
Any help would be very welcome!
Your mySheet variable is of Worksheet type while you are trying to use it as a String. Here is your loop improved:
For Each mysheet In Sourcebook.Worksheets
'Sourcebook.Sheets(mysheet).Range("I76:I133").Copy 'instead of this...
mysheet.Range("I76:I133").Copy '...use this
Destinationbook.Sheets(mysheet.Name).Range("I76").Paste
Next

Copy Row A1 from Sheet 1 into Row A1 Sheet 2

I basically just need to know how to copy a header from sheet one that goes from A1-O1 into sheet two, three, four, five and so on...they all have the same header. Sheet one is on the right and sheet two is left and increases to the left. I tried this which I found on some website but it says object required. The error is Runtime Error 424
mainworkBook.Sheets(“Sheet1”).Rows(1).EntireRow.Copy
mainworkBook.Sheets(“Sheet2”).Range(“A1”).Select
mainworkBook.Sheets(“Sheet2”).Paste
A small loop code.let me know if it works.
Sub COPYPASTeHEADER()
Dim K As Integer
For K = 2 To ActiveWorkbook.Sheets.Count
Sheets("All_Data").Range("A1:O1").COPY Sheets(K).Range("A1")
Next
End Sub
You can do something like this instead of using Select:
For Each Sheet In ThisWorkbook.Sheets
ThisWorkbook.Sheets("ALL_DATA").Rows(1).Copy Destination:=Worksheets(Sheet.Name).Range("A1")
Next
This will loop through each sheet in your workbook, take the range you provided (row 1 from Sheet1), and paste it to each sheet by referencing the Name property of each Sheet you are looping through.
The error may have been from the workbook variable, as that is the only thing that is unclear.
I would also recommend looking into this post: How to avoid using Select in Excel VBA macros as it is tremendously helpful in avoiding Select/Activate when possible, which is a common occurrence among those who learn VBA through recording Macros.
Let me know if it works for you.
This is an excellent place to use a loop. For each sheet in the workbook, paste the same header.
Sub forEachWs()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Call pasteContents(ws)
Next
End Sub
Sub pasteContents(ws as Worksheet)
** Your code goes here
End Sub
EDIT: The ** section could be as such:
Sub pasteContents(ws as Worksheet)
ActiveWorkbook.Sheets(“Sheet1”).Rows(1).EntireRow.Copy
ActiveWorkbook.Sheets(ws).Range(“A1”).Select
ActiveWorkbook.Sheets(ws).Paste
End Sub
Or it could also be...
Sub pasteContents(ws as Worksheet)
ActiveWorkbook.Sheets("Sheet1").Rows(1).Copy Destination:=Worksheets(ws).Range("A1")
End Sub

Dialog box that selects a worksheet in Excel

I'm trying to build a macro that will duplicate a worksheet from one workbook into a worksheet in another workbook. Is there a way I can use VBA code to allow me to manually select which worksheet I shall be duplicating?
Right now the macro works, as long as I have the full worksheet name typed into the actual VBA code. Ideally, I'd like the macro to allow me to select the worksheet through a dialog box. I know you can just copy/paste the sheet or its contents, but the guys I'm working for don't want to do that, due to the size.
You can use Worksheets collection to populate the ListBox in a user form. This should get you started:
Code in the user form (!):
Private Sub UserForm_Initialize()
Dim v As Worksheet
For Each v In Worksheets
UserForm1.lstWorksheets.AddItem v.Name
Next
End Sub
Private Sub cmdSelectWorksheet_Click()
MsgBox "You selected " & lstWorksheets.Value
End Sub

How to access a closed Excel Workbook using vlookup vba

I'm trying to create a Excel VBA macro that uses VLOOKUP to access a range of cells in a closed workbook. I'm not too good at using the VBA editor, but it doesn't seem to show a lot of useful information about errors.
Sub WorkBookWithData()
Dim currentWb As Workbook
Set currentWb = ThisWorkbook
Dim currentWs As Worksheet
Set currentWs = currentWb.Sheets(1)
Dim strFormula As String
strFormula = "=VLOOKUP(currentWs.Range("B2"),'Macintosh HD:Users:myself:Documents:l[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!A1:B222,2,false)"
currentWs.Range("C2").Formula = strFormula
End Sub
Excel VBA editor is hanging up on the "strFormula = "=VLOOKUP..." section.
Thanks
Reference from Siddharth Rout's comments.
The main problem in your code is this line:
strFormula = "=VLOOKUP(currentWs.Range("B2"),'Macintosh HD:Users:myself:Documents:l[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!A1:B222,2,false)"
because of this code currentWs.Range("B2"). We know that you want to indicate Range("B2") of Current Sheet(same sheet). So, you can use as follow:
strFormula = "=VLOOKUP(B2,'Macintosh HD:Users:myself:Documents:l[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!A1:B‌​222,2,false)"
Why? It can use just B2 because you set formula to a cell which is in the same sheet. So, it is not need to indicate the Sheet Name.
And If you want to set a cell which is from other sheet, you need to indicate Sheet Name in that case. So, should use as follow:
strFormula = "=VLOOKUP(" & currentWs.name & "!B2,'Macintosh HD:Users:myself:Documents:l[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!A1:B222,2,false)"
This looks nothing like what I had previously, but it works.
Sub Check_Master_Values()
Dim newCurWb As Workbook
Set newCurWb = Workbooks(2)
newCurWb.Activate
newCurWb.Sheets(1).Range("C2").Formula = "=VLOOKUP(B2,'Macintosh HD:Users:myself:Documents:[Master_Terms_Users.xlsm]Master_Terms_Users.csv'!$A$1:$B$269,2,FALSE)"
End Sub
In my first attempt, I didn't follow the chain of assignments from workbook, to sheets, to ranges. As you can see in this code, I Dim a new Workbook - then the big ah-ha moment, I needed to assign it to the correct open workbook. Then, I activated the workbook, and finally accessed the Sheets object and Range.
I also know now that my workbook selection number will vary depending on how many other workbooks are open. The ThisBook didn't work because somehow in the process, the workbook that ThisBook referenced, changed. That is probably also why my initial code didn't work, in addition to the improper coding in the VLOOKUP.
It would be good if there was a way to specify which workbook on the fly.
Thanks to everyone who gave help on the VLOOKUP part.