Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Using vlookup in vba

0

Hi,

I am trying to use a vlookup to look at a cell in each of my split sheets then pick a folder location stored in a vlookup on a sheet within the document.  I have done this by writing a vlookup as location then added & location to the file path.

it is sort of working but... it's saving all the files in the cell reference for the first split sheet rather than looking at each sheet so is saving them all in the same place! 

the code I am using is below. Any suggestions how I can edit this?  
the range in the lookup is a named range pointing to my lookup table 

thanks 

Sub Seperatesheets()
 
 Dim Ws As Worksheet
 Dim location As Variant
 Dim WsEligibilitySheets As Worksheet
 Dim wsfilesplitsheet As Worksheet
 Dim wbtosave As Workbook
 Dim filepathtosave As String
Application.ScreenUpdating = False
Set WsEligibilitySheets = Worksheets("Eligibility sheets")
 Set wsfilesplitsheet = Worksheets("File Split Sheet")
location = Application.WorksheetFunction.VLookup(Range("E2"), Range("lookuprange"), 2, 0)
filepathtosave = "C:\2024\Test\2024\" & location
 
 For Each Ws In ThisWorkbook.Worksheets
 If Ws.Name <> WsEligibilitySheets.Name Or Ws.Name <> wsfilesplitsheet.Name Then
 
     Ws.Copy
 
     Set wbtosave = ActiveWorkbook
    wbtosave.SaveAs _
         Filename:=filepathtosave & "2023 Eligibility Sheets Test2 " & wbtosave.Worksheets(1).Name & ".xlsx", _
         FileFormat:=51
wbtosave.Close True
End If
Next Ws
Application.ScreenUpdating = True
msgbox "complete"
End Sub
Answer
Discuss

Answers

0

 Hello Badgerkate and welcome to the forum.

You haven't uploaded a sample file so I need to make some assumptions - not the best way to provide an answer. Also, when including code in your post you should click "CODE" at the top of the window and then in what gets added, replace "Code_Goes_Here" with your code rather than putting it in your post.

After reviewing your code, the only needed change that stands out is the line:

filepathtosave = "C:2024\Test\2024\" & location

.

You have omitted a backslash in the file path.

Change that line to:

filepathtosave = "C:\2024\Test\2024\" & location

Update Mar. 2/24

After reviewing your file and code, and reviewing you additional details, I am still not completely clear as to how you want to go about this; but, after much trial and error I have come up with a possible solution. I have attached a copy of your file with my changes and code.

I have added a button to the "Eligibility sheet" which when clicked will run the macro. I added a worksheet called "Employee Roster" which has the same layout as the "Eligibility sheet". On the "Eligibility sheet" I added a helper column (col "O") to create an A to Z list of departments. The macro will search the "Eligibilty sheet" for each department, and then any employee in that department will be added to the "Employee Roster" sheet. When all employees have been checked, the roster sheet is saved to a new workbook, and the workbook is given the name of the department. That workbook is then saved. The following bit of code is what you will need to tweak to suit your situation.

Sheets("Employee Roster").Copy
    Set newWb = ActiveWorkbook
    newWb.Name = newWBname
    savePath = "C:\Users\HR\departments\" & newWBname & ".xlsx"
    newWb.SaveAs Filename:=savePath
    newWb.Close

Update Mar. 5/24

I have added 2 elements to the macro: 1) delete existing data on "Employee Roster" sheet before building new roster; 2) code to delete any unwanted colummns after the roster sheet is complete.

This may not be exactly what you had intended, but it gives you a good starting place.

If this solves things for you please mark my answer as Selected.

Cheers   :-)

Discuss

Discussion

Hi Willie, thanks for coming back so quickly. I redacted some of the file path as it was pointing to my one drive. The \ was there in the code and it does save into the 2024 master file before I added location to try and get the files to save in their indvidual sub folders. I'll update the code in my question.

thanks

kate
Badgerkate Feb 18, '24 at 3:42 am
Hi Badgerkate,
Thanks for updating the way your code is posted. In your original post the backslash after "C:" was not there that is why I posted what I did. Have you got it working? If not, it will be 2-3 days before I can take a deeper look.

Cheers   :-)
WillieD24 (rep: 557) Feb 18, '24 at 9:45 am
No but I think after sleeping on it I'm a bit closer, or at least I think I can explain my problem a little better. I think the issue is the initial cell reference, E2 in the lookup. I'm a little confused how it knows which E2 as the master sheet with all my data on (eligibility sheets) is split maybe 50 times based on the value in E2. I think it's saying okay ignore eligibility sheets and file split sheet and is looking for the first available e2 and is then only performing the vlookup once rather than for each sheet rather than repeating using cell e2 on the next sheet to save.  I think I need to somehow tell it once it copies and saves the first tab to repeat the vlookup on the next active sheet. And that's where I'm coming stuck. Maybe there's a better way than doing a vlookup to determine the folder structure but can't think.

thanks for any help you can give. I'm pretty good with excel but vba is a whole new challenge
Badgerkate Feb 18, '24 at 10:46 am
@Willie - took a quick glance at this but it's tricky to solve without a file (and I don't have the time to understand the last Discussion point!). The thing I'd check is that the VLookup produces a value (for the variable location) which ends in  a backslash / (to give a proper path for the file) and isn't an error. If not, you could add
& "/ &
 within the Filename argument.


@Kate - Willie is more than capable of solving problems like this but it would really help him (to help you) if you provided a test file, with your worksheet structure and some dummy data (maybe just 10 representative items). To do do, edit your original question and use the Add Files button.
John_Ru (rep: 6142) Feb 19, '24 at 5:01 pm
@Kate, @ John

I don'y have the time today, but I believe the line "location = . . . " needs some fixing/tweaking and the "save" loop also needs some fixing/tweaking. I will take a deeper look in a day or 2.

Cheers   :-)
WillieD24 (rep: 557) Feb 19, '24 at 7:18 pm
Hi Kate,

Need some clarification before I put too much effort into this.
There are 2 worksheets in your workbook that you don't want to save - "Eligibility sheets" and "File Split Sheet" - correct? From left to right, are these the first 2 worksheets? What is the total number of worksheets in the file (workbook)?
On which worksheet are the "E2" and "lookuprange" references found?
Do you want each sheet saved to its own file (workbook) or have all sheets saved to the same file (workbook)?
These details will help me amend your code.
WillieD24 (rep: 557) Feb 19, '24 at 11:36 pm
Hi Kate,

Another couple of things that need clarification.
You use the variable "location" to store the result of the vlookup but you have not declared it so VBA doesn't know what type "location" is. What is an example of what the vlookup returns? A value? Text? The syntax of your SaveAs also needs a bit of tweaking, but I need my questions answered before I will suggest a fix.

Cheers   :-)
WillieD24 (rep: 557) Feb 20, '24 at 7:56 pm
Hi,

sorry for the delayed response.. I really don't know where this week has gone. managed to access your site through my work pc so am able to share a blank copy of my template.  it has two macros currently live, one which splits the sheets by area in col E of the eligibility sheets based on a named range located in the file split sheets which is simple but does what it needs to do - it gives us a seperate sheet based on each location. macro number two then saves each of the sheets and we are then manually moving it into the named folder based on a folder location, but I wanto to automate this to auto save it in its own folder rather than manually having to insert each one as its creating approx 50 files. so ive added a file path inot the split sheets I managed to get it to run but it is putting htem all in the cell of E5 on the first split sheet rather than repeating the vlookup for each sheet and saving it based on the file path in the vlookup. the eligibility file is the master file and the file split sheets is holding the macro data so when I split out I want to exclude these as they are effectvily redudant once we have each of the dept files for distribution so we are takign one master data file and creating 50ish new sheets from the data. I think this answers all of your points but if I have missed anythign please let me know.
Badgerkate Feb 22, '24 at 4:48 pm
Hi Kate,

Thanks for the update and uploading a file. It's not likely I will be able to look at it until next week. If I can get to it sooner I will.
Check back next week.
Cheers
WillieD24 (rep: 557) Feb 22, '24 at 5:04 pm
Thanks for agreeing to take a look
snd try and help. Honnestly no rush at all :)
Badgerkate Feb 22, '24 at 5:35 pm
Hi Kate,   Firstly, this is not my site. This site is owned by a fellow named Don. I am just a forum member like yourself, and I voluntarily provide help where I can to those having problems. The only compensation is when someone we help selects our answer. I took a quick look at your fileand need a bit more clarification.  Your “Eligibility” worksheet is setup to have 1,974 records (rows 4 to 1978) – are these unique entries or are there repeats? If there are repeated entries, what do you want to happen when a duplicate is encountered? Is it your aim to look for each entry in E4:E1978 of the “Eligibility” sheet, on the ‘split’ sheet (A2:A70) and then create a new file for each time it is found?
WillieD24 (rep: 557) Feb 25, '24 at 11:15 am
Hi Willie, so each row would be a unique person but depts would be repeated. to splitthe sheets I have been pasting the contents of col e into cola of the split sheet and removing duplicates so I just  have alist of unique depts in the named range then splitting the sheets. e.g all people team on one sheet, finance eon another and so on. I think want to use the dept name which the sheet is renamed as and find that in the split sheet list and save it to the destination in the nect col. hope that makes sense. thanks

Kate 
Badgerkate Feb 26, '24 at 10:27 am
Hi Kate,

Thanks for your patience. VBA is an amazing tool and there is always more than one way to achieve a goal. To be able to put together a possible solution I need to fully understand your end goal.
This is how I understand what you have said. You have hundreds of employees working in many different (let's say 70) departments. You want to create a worksheet for each dept. which lists all the employees in that dept. Correct? You want that worksheet renamed for the dept. name. Correct? You want all of these sheets stored in another workbook. Correct? What other info do you want included on each dept. sheet? On your "file split sheet" worksheet how does info get populated to col "C", "D", "E", and "F"? Also, what exactly do you mean by "splitting the sheets"?
WillieD24 (rep: 557) Feb 26, '24 at 10:14 pm
1/2 Hi Willie thats correct, so I have a tab in my master document for each project and then using various filters I take the info I need. so in this example its some basic employee data plus their eligibility status, i.e bonus for pay review for example. i'm then taking that sheet and pasting it into a new document which holds my macros (eventually when I get better id like to run it within my master doc, but baby steps) my first macro is then making a copy of the data in the master data tab but filtering it by dept and renaming the tab by department. 
Badgerkate Feb 29, '24 at 8:36 am
2/2i've kept this sperate to the macro we are looking at as it makes it easier for us to double check the final data with less people on each tab. once we are happy I then want to take all of the new sheets ive created and save them as inidvidual  which my macro is doing but it saving them all in the same place and we are then manually moving them into each depts folder for review. I am trying to adjust my macro to take this manual step out and tell it the individual file path to save the documents rather than someone having to move them. if we didnt have subfolders I think this would be quite simple as I could just have a folder which matches the worksheet name but there are a few sub folders e.g london then in that london north and south and then broken down again within that which is why I need to store the worksheet name somewhere ( this is already in the split sheet tab as I use thi as part of my first macro to split the data into each dept) and the file path once it individualises which i've tried to add to split sheet. I have seen it done before so know it can be done I just can't quite picture how to get there.

Hope my waffle makes sense

Kate
Badgerkate Feb 29, '24 at 8:36 am
Hi Kate,

Sorry this took so long. Please see my answer above and Update Mar.2/24.
WillieD24 (rep: 557) Mar 2, '24 at 9:34 pm
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login