Iterate through Data Validation List - vba

i created a button which is this macro on it:
Sub loopthroughvalidationlist()
Dim inputRange As Range
Dim c As Range
Set inputRange = Evaluate(Range("A9").Validation.Formula1)
path = "C:\test\"
For Each c In inputRange
filename1 = Range("B18").Text
ActiveWorkbook.SaveCopyAs filename:=path & filename1 & ".xlsm"
Next c
End Sub
the list of the validation contains about 5 names. but for some reason it only saves 1 file.

As far as you are not having problems with accessing the data validation list, I have hardcoded it in Range("A1:A5").
I have changed ActiveWorkbook with ThisWorkbook to see how it works as well.
-ThisWorkbook.Save is needed to produce valid .FullName and valid .Path
The tricky part is to save the oldPathFull and the oldPath of the excel file and to use ThisWorkbook.SaveAs oldPathFull on every loop.
Application.DisplayAlerts = False disables the Excel prompts. You can put it outside the loop, if you feel like it.
Sub LoopThroughValidationList()
Dim inputRange As Range
Dim c As Range
Dim oldPathFull As String
Dim oldPath As String
Set inputRange = Range("A1:A5")
ThisWorkbook.Save
oldPathFull = ThisWorkbook.FullName
oldPath = ThisWorkbook.Path & "\"
For Each c In inputRange
Application.DisplayAlerts = False
ThisWorkbook.SaveCopyAs Filename:=oldPath & c & ".xlsb"
ThisWorkbook.SaveAs oldPathFull
Application.DisplayAlerts = True
Next c
End Sub
Once you are able to get the code running with predefined values, this is a [MCVE] example how to get the data validation values of a cell B1:
Public Sub TestMe()
Dim myCell As Range
Dim valRules As Range
Set valRules = Evaluate(Range("A1").Validation.Formula1)
For Each myCell In valRules
Range("A1") = myCell
Debug.Print Range("A1")
Next myCell
End Sub

Related

combine multiple text files in a single excel sheet

I have 27 txt files with the same format and columns, and I want to append all of these in a single excel sheet. I have checked some previous threads here, but I could only find the code below which helped me to import txt fiels into separate sheets. However, I also want to append these separate sheets into a sheet that I want to append all my data.
Sub Test()
'UpdatebyExtendoffice6/7/2016
Dim xWb As Workbook
Dim xToBook As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Dim xFiles As New Collection
Dim I As Long
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder [Vendor_data_25DEC]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
xFile = Dir(xStrPath)
'xFile = Dir(xStrPath & "*.txt") 'this is the original version that you can amend according to file extension
If xFile = "" Then
MsgBox "No files found", vbInformation, "Vendor_data_25DEC"
Exit Sub
End If
Do While xFile <> ""
xFiles.Add xFile, xFile
xFile = Dir()
Loop
Set xToBook = ThisWorkbook
If xFiles.Count > 0 Then
For I = 1 To xFiles.Count
Set xWb = Workbooks.Open(xStrPath & xFiles.Item(I))
xWb.Worksheets(1).Copy after:=xToBook.Sheets(xToBook.Sheets.Count)
On Error Resume Next
ActiveSheet.Name = xWb.Name
On Error GoTo 0
xWb.Close False
Next
End If
End Sub
I am not sure how to do this with VBA in order to combine the data in separate sheets into a single sheet quickly. I know the consolidate feature of excel but it also includes lots of manual steps, so I seek for a faster and automated solution. Any help is much appreciated.
Thanks a lot in advance.
Sub Combiner()
Dim strTextFilePath$, strFolder$
Dim wksTarget As Worksheet
Dim wksSource As Worksheet
Dim x As Long
Set wksTarget = Sheets.Add()
strFolder = "c:\Temp\test\"
strTextFilePath = Dir(strFolder)
While Len(strTextFilePath) > 0
'// "x" variable is just a counter.
'// It's purpose is to track whether the iteration is first or not.
'// If iteration is first (x=1), then we include header (zero offset down),
'// otherwise - we make an offset (1 row offset down).
x = x + 1
Set wksSource = Workbooks.Open(strFolder & strTextFilePath).Sheets(1)
With wksTarget
wksSource.Range("A1").CurrentRegion.Offset(IIf(x = 1, 0, 1)).Copy _
.Cells(.Rows.Count, 1).End(xlUp).Offset(1)
End With
wksSource.Parent.Close False
strTextFilePath = Dir()
Wend
MsgBox "Well done!", vbInformation
End Sub

Splitting an identified range of spreadsheets to a new workbook with a new name

I've been trying to come up with a way to split a workbook into separate workbooks based on identified worksheets in the workbook.
For example:
Say I had a worksheet for every letter in the alphabet.
I would want to split worksheets A through C into a new workbook named "A through C."
D through I will go into a new workbook named "D through I."
etc...
My idea would be to first insert a worksheet that in column A names the new workbook it will become and Columns b through as many columns as there are will the names of the worksheets to be copied into the new workbook.
Does anyone have an idea of how to make a macro for this? I've tried myself but have been unsuccessful.
Thank you!
I found this Macro out there. Does anyone think it can be modified to work?
Sub Test()
Dim Sh As Worksheet
Dim Rng As Range
Dim c As Range
Dim List As New Collection
Dim Item As Variant
Dim WB As Workbook
Application.ScreenUpdating = False
Set Sh = Worksheets("Sheet1")
Set Rng = Sh.Range("A2:A" & Sh.Range("A65536").End(xlUp).Row)
On Error Resume Next
For Each c In Rng
List.Add c.Value, CStr(c.Value)
Next c
On Error GoTo 0
Set Rng = Sh.Range("A1:H" & Sh.Range("A65536").End(xlUp).Row)
For Each Item In List
Set WB = Workbooks.Add
Rng.AutoFilter Field:=1, Criteria1:=Item
Rng.SpecialCells(xlCellTypeVisible).Copy WB.Worksheets(1).Range("A1")
Rng.AutoFilter
With WB
.SaveAs ThisWorkbook.Path & "\" & Item & ".xls"
.Close
End With
Next Item
Sh.Activate
Application.ScreenUpdating = True
End Sub
The following code assumes you have your control sheet (named "Split Parameters") in the workbook containing the macro, and it is set out with the desired filenames in column A, and the sheets that you wish to copy into that file (from the ActiveWorkbook, which might, or might not, be the one containing the macro) listed in columns B, C, etc. Row 1 is assumed to be headings, and is therefore ignored.
Sub SplitBook()
Dim lastRow As Long
Dim LastColumn As Long
Dim srcWB As Workbook
Dim newWB As Workbook
Dim i As Long
Dim c As Long
Dim XPath As String
Dim newName As String
Dim sheetName As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set srcWB = ActiveWorkbook
XPath = srcWB.Path
With ThisWorkbook.Worksheets("Split Parameters")
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = 2 To lastRow
'Take the first worksheet and create a new workbook
sheetName = .Cells(i, "B").Value
srcWB.Sheets(sheetName).Copy
Set newWB = ActiveWorkbook
'Now process all the other sheets that need to go into this workbook
LastColumn = .Cells(i, .Columns.Count).End(xlToLeft).Column
For c = 3 To LastColumn
sheetName = .Cells(i, c).Value
srcWB.Sheets(sheetname).Copy After:=newWB.Sheets(newWb.Sheets.Count)
Next
'Save the new workbook
newName = .Cells(i, "A").Value
newWB.SaveAs Filename:=xPath & "\" & newName & ".xls", FileFormat:=xlExcel8
newWB.Close False
Next
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

errors pulling key information from multiple excel workbooks

I am attempting to write a macro in a workbook whose purpose is to display the key information from each of a set of excel files. the first column contains the name of the file which will be used in the code.
the code I have written so far should loop through the list of 11 file names in the summary sheet and pull the info called from cell E21 in each of those files and place it in cell Hx in the summary sheet.
I have had no luck getting it to work so far, my first error im getting is "invalid Qualifier" on the line that says "MySheet". I know that there are alot of other mistakes here as I have never attempted to write a sub that pulls from other closed workbooks.
My code is as follows:
Option Explicit
Sub OEEsummmary()
Dim Gcell As Range
Dim Txt$, MyPath$, MyWB$, MySheet$
Dim myValue As Integer
Dim x As Long
Dim v As Variant, r As Range, rWhere As Range
MyPath = "L:\Manufacturing Engineering\Samuel Hatcher\"
x = 2
MySheet = ActiveSheet.Name
Application.ScreenUpdating = False
Do While MySheet.Range("A" & x).Value <> ""
MyWB = MySheet.Range("A" & x).Txt
Workbooks.Open Filename:=MyPath & MyWB
Set Gcell = ActiveSheet.Range("E21")
With ThisWorkbook.ActiveSheet.Range("A" & x)
.Value = "Item"
.Offset(7, 0).Value = Gcell.Value
End With
ActiveWorkbook.Close savechanges:=False
x = x + 1
Loop
End Sub
Ive looked at what an invalid qualifier error is and i dont understand what i have wrong with that part of my code. Any help with this and any other blinding errors would be greatly appreciated!
The issue I see that's causing the Invalid Qualifier error is that you are declaring MySheet as a string, but trying to use it as a Worksheet object. Below I've declared it as a worksheet and set it to the Activesheet. I also changed the ThisWorkbook.ActiveSheet reference to MySheet, which I think is what you want. Also changed Txt to Text:
Sub OEEsummmary()
Dim Gcell As Range
Dim MySheet As Worksheet
Dim Txt$, MyPath$, MyWB$
Dim myValue As Integer
Dim x As Long
Dim v As Variant, r As Range, rWhere As Range
MyPath = "L:\Manufacturing Engineering\Samuel Hatcher\"
x = 2
Set MySheet = ActiveSheet
Application.ScreenUpdating = False
Do While MySheet.Range("A" & x).Value <> ""
MyWB = MySheet.Range("A" & x).Text
Workbooks.Open Filename:=MyPath & MyWB
Set Gcell = ActiveSheet.Range("E21")
With MySheet.Range("A" & x)
.Value = "Item"
.Offset(7, 0).Value = Gcell.Value
End With
ActiveWorkbook.Close savechanges:=False
x = x + 1
Loop
End Sub

How to import excel data into new workbook?

I am trying to combine multiple excel files into one file. I am able to do that correctly, but the location I want to place the data is running into a small problem.
I want my data to start (paste) at cell A2 under the header row, but since my sheet is formatted as a table with a named range, my data is pasted just below the last line of that blank table. This is the code I'm using to paste the data.
Sub CombineFiles()
Dim path As String, ThisWB As String, lngFilecounter As Long
Dim wbDest As Workbook, shtDest As Worksheet, ws As Worksheet
Dim Filename As String, Wkb As Workbook
Dim CopyRng As Range, Dest As Range
Dim RowofCopySheet As Integer
ThisWB = ActiveWorkbook.Name
path = "C:\MyFolder"
RowofCopySheet = 2
Application.EnableEvents = False
Application.ScreenUpdating = False
Set shtDest = ActiveWorkbook.Sheets("Import")
Range("A2").Select
Filename = Dir(path & "\*.xl??", vbNormal)
If Len(Filename) = 0 Then Exit Sub
Do Until Filename = vbNullString
If Not Filename = ThisWB Then
Set Wkb = Workbooks.Open(Filename:=path & "\" & Filename)
Set CopyRng = Wkb.Sheets(1).Range(Cells(RowofCopySheet, 1), Cells(Cells(Rows.Count, 1).End(xlUp).Row, Cells(1, Columns.Count).End(xlToLeft).Column))
Set Dest = shtDest.Range("A" & shtDest.Cells(Rows.Count, 1).End(xlUp).Row + 1)
CopyRng.Copy
Dest.PasteSpecial xlPasteFormats
Dest.PasteSpecial xlPasteValuesAndNumberFormats
Application.CutCopyMode = False 'Clear Clipboard
Wkb.Close False
End If
Filename = Dir()
Loop
Sheets("Import").Select
Range("A1").Select
End Sub
Is there any change I can make to the code or the contents of the cells in the table to allow this to work correctly? Thanks for the help!
Please try this after changing range to your requirements. It will paste from A2. Using the clipboard takes time and resources so the best way would be to avoid a copy and paste and just set the values equal to what you want.Though you have mentioned that data transfer is required between separate workbooks but mentioned code for only basic problem, so this code fragment conveys the basic concept for transfer in a situation where there is a named table involved.
Sub Normalize()
Dim CopyFrom As Range
Set CopyFrom = Sheets("Sheet2").Range("A2", [H30])
Sheets("Sheet1").Range("A1").Resize(CopyFrom.Rows.Count).Value = CopyFrom.Value
End Sub

Copy Cells from 2 or more workbooks to a new workbook

I am trying to write some code which copies cells C24, C25 and D24, D25 from all the .xls files from location "C:\MyPath\" and I'm new to using VBA but I was looking for some solution online and was able to make up some code which combines all excel files in a folder and copies it to single workbook with each workbook going into each sheet.
Th code I worked on is
Option Explicit
Sub CopyWorksheets()
Const sPath = "C:\MyPath\"
Dim sFile As String
Dim wbkSource As Workbook
Dim wSource As Worksheet
Dim wbkTarget As Workbook
On Error GoTo ErrHandler
Application.ScreenUpdating = False
Set wbkTarget = ActiveWorkbook
sFile = Dir(sPath & "*.xls*")
Do While Not sFile = ""
Set wbkSource = Workbooks.Open(Filename:=sPath & sFile, AddToMRU:=False)
For Each wSource In wbkSource.Worksheets
With wbkTarget
wSource.Copy After:=.Sheets(.Sheets.Count)
End With
Next
wbkSource.Close SaveChanges:=False
sFile = Dir
Loop
ExitHandler:
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitHandler
End Sub
May I know the changes or additions to the above code to get my solution?
I copied your code to a new workbook. I renamed worksheet Sheet1 as C24D25 and created a header row:
A B C D E F
1 Workbook Worksheet C24 D24 C25 D25
At the top of your routine I added the extra variables and constants I required:
Const colTgtWbk As Long = 1
Const colTgtWsht As Long = 2
Const colTgtC24 As Long = 3
Const colTgtC25 As Long = 5
Dim wshtTarget As Worksheet
Dim rowTgtCrnt As Long
Set wshtTarget = ActiveWorkbook.Worksheets("C24D25")
rowTgtCrnt = 2
Replace “C24D25” with your name for the worksheet into which values are collected.
I amended the definition of sPath to a folder on my laptop containing several workbooks.
Near the top of your code I commented out:
'On Error GoTo ErrHandler
and near the end I commented out:
'ExitHandler:
'Exit Sub
'ErrHandler:
'MsgBox Err.Description, vbExclamation
'Resume ExitHandler
I never include my own error handler during development and I never include one in a production macro unless I have discovered a need during development. An error handler routine is not the best method for handling errors you expect and can test for. They should be reserved for errors you cannot test for such as attempting to open a file for which you may not have read permission.
Around your main block:
Set wbkSource = Workbooks.Open(Filename:=sPath & sFile, AddToMRU:=False)
to
wbkSource.Close SaveChanges:=False
I added an If:
If sFile <> wbkTarget.Name Then
End If
This avoids attempting to reopen the workbook in which you are collecting data.
I deleted:
With wbkTarget
wSource.Copy After:=.Sheets(.Sheets.Count)
End With
and replaced this code with:
With wshtTarget
.Cells(rowTgtCrnt, colTgtWbk).Value = wbkSource.Name
.Cells(rowTgtCrnt, colTgtWsht).Value = wSource.Name
wSource.Range("C24:D24").Copy Destination:=.Cells(rowTgtCrnt, colTgtC24)
wSource.Range("C25:D25").Copy Destination:=.Cells(rowTgtCrnt, colTgtC25)
rowTgtCrnt = rowTgtCrnt + 1
End With
This is the code that builds the rows in worksheet C24D25.
At the bottom I added:
wshtTarget.Columns.AutoFit
This expands the columns to the width of the data found.
The result of the changes above is:
Option Explicit
Sub CopyWorksheets()
Const colTgtWbk As Long = 1
Const colTgtWsht As Long = 2
Const colTgtC24 As Long = 3
Const colTgtC25 As Long = 5
Dim wshtTarget As Worksheet
Dim rowTgtCrnt As Long
Set wshtTarget = ActiveWorkbook.Worksheets("C24D25")
rowTgtCrnt = 2
Const sPath = "C:\DataArea\SOTest\Excel\"
Dim sFile As String
Dim wbkSource As Workbook
Dim wSource As Worksheet
Dim wbkTarget As Workbook
Application.ScreenUpdating = False
Set wbkTarget = ActiveWorkbook
sFile = Dir(sPath & "*.xls*")
Do While sFile <> ""
If sFile <> wbkTarget.Name Then
Set wbkSource = Workbooks.Open(Filename:=sPath & sFile, AddToMRU:=False)
For Each wSource In wbkSource.Worksheets
With wshtTarget
.Cells(rowTgtCrnt, colTgtWbk).Value = wbkSource.Name
.Cells(rowTgtCrnt, colTgtWsht).Value = wSource.Name
wSource.Range("C24:D24").Copy Destination:=.Cells(rowTgtCrnt, colTgtC24)
wSource.Range("C25:D25").Copy Destination:=.Cells(rowTgtCrnt, colTgtC25)
rowTgtCrnt = rowTgtCrnt + 1
End With
Next
wbkSource.Close SaveChanges:=False
End If
sFile = Dir
Loop
wshtTarget.Columns.AutoFit
Application.ScreenUpdating = True
End Sub
I hope the purposes of the changes I have made are obvious, Ask questions if necessary.