Extracting a range of non-contiguous cells - excel

Extracting a range of non-contiguous cells within number of excel files in a particular folder (data has to be pulled from either of 2 UNIQUE SHEETS)
I have the below code for pulling data (range of cells) that are non-contiguous and pasting them in a new sheet. However, the code needs to look for the data in either of the 2 sheets , namely - "summary1" or "extract1".
[Note- Only one of the two sheets would be available in each file]
I can successfully pull for one of them but if i add both of them using "On Error Resume Next" i get an error. Kindly guide me on how to resolve this!
Any suggestions or tips are much appreciate!!
Code:
Sub PIdataextraction()
Dim myFile As String, path As String
Dim erow As Long, col As Long
path = "C:\Users\New\"
myFile = Dir(path & "*.xl??")
Application.ScreenUpdating = False
Do While myFile <> ""
Workbooks.Open (path & myFile)
Windows(myFile).Activate
Set copyrange = Sheets("summary1").Range("B4,E7,E9,E11,E13,E15,I12,J22,C24,C25,C26,I11,R16")
On Error Resume Next
Set copyrange = Sheets("extract1").Range("B4,E7,E9,E11,E13,E15,I12,J22,C24,C25,C26,I11,R16")
Windows("MasterFile.xlsm").Activate
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
col = 1
For Each cel In copyrange
cel.Copy
Cells(erow, col).PasteSpecial xlPasteValues
col = col + 1
Next
Windows(myFile).Close savechanges:=False
myFile = Dir()
Loop
Range("A:E").EntireColumn.AutoFit
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Data has been Compiled,Please Check!"
End Sub

Here's one approach which factors out the "find one of these sheets in a workbook" logic into a separate function.
Sub PIdataextraction()
Const PTH As String = "C:\Users\New\" 'use const for fixed values
Const RNG As String = "B4,E7,E9,E11,E13,E15,I12,J22,C24,C25,C26,I11,R16"
Dim myFile As String, path As String, c As Range
Dim erow As Long, col As Long, wb As Workbook, ws As Worksheet
Application.ScreenUpdating = False
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).row
myFile = Dir(PTH & "*.xl??")
Do While myFile <> ""
Set wb = Workbooks.Open(path & myFile)
Set ws = FindFirstSheet(wb, Array("summary1", "extract1"))
If Not ws Is Nothing Then 'check we got a sheet
col = 1
For Each c In ws.Range(RNG).Cells
Sheet1.Cells(erow, col).Value = c.Value
col = col + 1
Next c
Sheet1.Cells(erow, col).Value = wb.Name '<<<<<<<<<<<<<<<<
erow = erow + 1
Else
Debug.Print "No sheet found in " & ws.Name
End If
wb.Close savechanges:=False
myFile = Dir()
Loop
Range("A:E").EntireColumn.AutoFit
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Data has been Compiled,Please Check!"
End Sub
'Given a workbook `wb`, return the first sheet found from
' an array of sheet names `SheetNames`
Function FindFirstSheet(wb As Workbook, SheetNames) As Worksheet
Dim ws As Worksheet, s
For Each s In SheetNames
On Error Resume Next
Set ws = wb.Worksheets(s)
On Error GoTo 0
If Not ws Is Nothing Then Exit For
Next s
Set FindFirstSheet = ws
End Function

The following code worked for me. As usual thank you for your valuable inputs!! much appriciated
Sub PIdataextraction()
Dim myFile As String, path As String
Dim erow As Long, col As Long
Dim shtSrc As Worksheet
Dim copyrange As Range, cel As Range
path = "C:\Users\New\"
myFile = Dir(path & "*.xl??")
Application.ScreenUpdating = False
Do While myFile <> ""
Workbooks.Open (path & myFile)
Windows(myFile).Activate
On Error Resume Next
Set shtSrc = Worksheets("summary1")
If Err = 9 Then
On Error Resume Next
Set shtSrc = Worksheets("extract1")
If Err = 9 Then Exit Sub
On Error GoTo 0
End If
Set copyrange = shtSrc.Range("B4,E7,E9,E11,E13,E15,I12,J22,C24,C25,C26,I11,R16")
Windows("MasterFile.xlsm").Activate
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
col = 1
For Each cel In copyrange
Cells(erow, col).Value = cel.Value ' Equivalent of xlPasteValues
col = col + 1
Next
Windows(myFile).Close savechanges:=False
myFile = Dir()
Loop
Range("A:E").EntireColumn.AutoFit
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Data has been Compiled,Please Check!"
End Sub

Related

Open workbooks and move & copy a worksheet into a new workbook

I'm trying to write a code to open mentioned workbooks one by one and move & copy a particular worksheet into a new workbook
my code for the above mentioned task runs well till it opens the first file, then it gives me the following error
method or data member not found
Sub OpenFilesMoveCopyWorksheet()
Const PTH As String = "C:\Users\xxx\yyy\" 'use const for fixed values
Dim SFile As Workbook, SFname As Worksheet, SFname2 As Worksheet
Dim SFlname As String, I As Long, DFile As Workbook
Dim Acellrng As Range, ws As Worksheet, rngDest As Range, rngCopy As Range
Set SFile = ThisWorkbook
Set SFname = SFile.Worksheets("Sheet1")
Application.ScreenUpdating = False
For I = 1 To SFname.Cells(Rows.Count, "A").End(xlUp).Row
SFlname = SFname.Range("A" & I).Value
If Len(SFlname) > 0 Then
Set DFile = Workbooks.Open(PTH & SFlname)
If DFile.Worksheets.Name Like "*.cours" Then
DFile.Worksheet.copyafter: SFile.SFname
End If
DFile.Close savechanges:=False
End If
Next I
MsgBox "job done"
Application.ScreenUpdating = True
End Sub
Modified the code still getting "Run-time error'-2147221080 (800401a8)': Automation error"
Sub OpenFilesMoveCopyPaste()
Const PTH As String = "C:\xxx\yy\" 'use const for fixed values
Dim SFile As Workbook, SFname As Worksheet, SFname2 As Worksheet
Dim SFlname As String, I As Long, DFile As Workbook, I1 As Long, SFlname2 As String
Dim Acellrng As Range, ws As Worksheet, rngDest As Range, rngCopy As Range
Set SFile = ThisWorkbook
Set SFname = SFile.Worksheets("Sheet1")
Application.ScreenUpdating = False
For I = 1 To SFname.Cells(Rows.Count, "A").End(xlUp).Row
SFlname = SFname.Range("A" & I).Value
If Len(SFlname) > 0 Then
Set DFile = Workbooks.Open(PTH & SFlname)
For I1 = 1 To SFname.Cells(Rows.Count, "B").End(xlUp).Row
SFlname2 = SFname.Range("B" & I1).Value
If Len(SFlname2) > 0 Then
Set ws = DFile.Worksheets(SFlname2)
ws.copy Before:=SFile.Sheets("sheet1")
DFile.Close savechanges:=False
End If
Next I1
End If
Next I
MsgBox "job done"
Application.ScreenUpdating = True
End Sub
Final Version
Sub OpenFilesMoveCopyPasteSpecial()
Const PTH As String = "C:\XXX\YY\" 'use const for fixed values
Dim SFile As Workbook, SFname As Worksheet, SFname2 As Worksheet
Dim SFlname As String, I As Long, DFile As Workbook, I1 As Long, SFlname2 As String
Dim Acellrng As Range, ws As Worksheet, rngDest As Range, rngCopy As Range
Application.DisplayAlerts = False
Set SFile = ThisWorkbook
Set SFname = SFile.Worksheets("Sheet1")
Application.ScreenUpdating = False
For I = 1 To SFname.Cells(Rows.Count, "A").End(xlUp).Row
SFlname = SFname.Range("A" & I).Value
If Len(SFlname) > 0 Then
Set DFile = Workbooks.Open(PTH & SFlname)
Debug.Print DFile.Name
SFlname2 = SFname.Range("B" & I).Value
Set ws = DFile.Worksheets(SFlname2)
ws.copy After:=SFile.Sheets("sheet1")
Cells.Select
Range("AO1").Activate
Selection.copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
DFile.Close savechanges:=False
End If
Next I
MsgBox "job done"
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

The file name of the excel workbooks the Macro pulls data from to be recorded

I would want the file names to be recorded in the "MasterFile" next to the data pulled from the respective files, so that i can map data items to the file names.
Any guidance/ ideas are much appreciated!! Thanks in advance :)
Code:
Sub PIDataExtraction()
Dim myFile As String, Path As String
Dim erow As Long, col As Long
Dim shtSrc As Worksheet
Dim copyrange As Range, cel As Range
fpath = Range("B2").Value
myFile = Dir(Path & "*.xl??")
Application.ScreenUpdating = False
Do While myFile <> ""
Workbooks.Open (Path & myFile)
Windows(myFile).Activate
On Error Resume Next
Set shtSrc = Worksheets("RX Ratings Price Calculator")
If err = 9 Then
On Error Resume Next
Set shtSrc = Worksheets("Feed Content Pricing Guideline")
If err = 9 Then Exit Sub
On Error GoTo 0
End If
Set copyrange = shtSrc.Range("B4,E7,E9,E11,E13,E15,Ratings_Universe_Default,J22,C24,C25,C26,I11,R16")
Windows("MasterFile.xlsm").Activate
erow = Data.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
col = 1
For Each cel In copyrange
Cells(erow, col).Value = cel.Value
col = col + 1
Next
Windows(myFile).Close savechanges:=False
myFile = Dir()
Loop
Range("A:E").EntireColumn.AutoFit
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Data has been Compiled,Please Check!"
End Sub

VBA copy/paste loop not pulling anything

I've only been at VBA for about 2 weeks so I need some assistance. I have a loop setup to copy 7 cells across on workbook (A), then paste them vertically in a column on workbook (B). For some reason the code is working but will not paste any data... I've been trying to troubleshoot for a while now with no luck.
Here is a screenshot of the sheet I'm copying data from.
Here is a screenshot of the workbook I'm pasting too.
Sub pullSecEquipment()
Dim path As String
Dim ThisWB As String
Dim wbDest As Workbook
Dim shtDest As Worksheet
Dim Filename As String
Dim Wkb As Workbook
Dim CopyRng As Range, DestRng As Range
Dim lRow As Integer
Dim destLRow As Integer
Dim UpdateDate As String
ThisWB = ActiveWorkbook.Name
Dim selectedFolder
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
selectedFolder = .SelectedItems(1) & "\"
End With
path = selectedFolder
Application.EnableEvents = False
Application.ScreenUpdating = False
Set shtDest = Workbooks("GPnewchapterTEST2.xlsm").Worksheets("START")
'clear content of destination table
shtDest.Rows("8:" & Rows.Count).ClearContents
Filename = Dir(path & "\*.xls*", vbNormal)
If Len(Filename) = 0 Then Exit Sub
Do Until Filename = vbNullString
Set Wkb = Workbooks.Open(Filename:=path & "\" & Filename)
'MsgBox Filename
'''''
'SEC
'''''
If InStr(Filename, "Equipment") <> 0 Then
'''
'' Equipment Hours
'''
Dim range1 As Range
Set range1 = Range("E:K")
If shtDest.Name Like "*-*" Then
'last row
destLRow = Wkb.Sheets(1).Cells.Find(what:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row
'1st row
lRow = Wkb.Sheets(1).Cells.Find(what:="EQUIPMENT DESCRIPTION", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
Dim i As Integer
For i = lRow To destLRow
Set CopyRng = Wkb.Sheets(1).Range(Cells(i, 5).Address, Cells(i, 11).Address)
Set DestRng = shtDest.Range("O" & shtDest.Cells(Rows.Count, 1).End(xlUp).Row + 1)
CopyRng.Copy
DestRng.PasteSpecial Transpose:=True
Application.CutCopyMode = False 'Clear Clipboard
i = i + 2
Next i
End If
End If
Filename = Dir()
Loop
MsgBox "Done!"
End Sub

Need to copy values with no formula - been working on it all night and cant do it

Need to copy values with no formula currently getting value error coming up - been working on it all night and cant do it
Sub LoopThrough()
Dim MyFile As String, Str As String, Mydir As String, Wb As Workbook
Dim Rws As Long, Rng As Range
Set Wb = ThisWorkbook
'change address to suite
Mydir = "C:"
MyFile = Dir(Mydir & "*.xlsm")
ChDir Mydir
Application.ScreenUpdating = 0
Application.DisplayAlerts = 0
Do While MyFile <> ""
Workbooks.Open (MyFile)
With Worksheets("IDS_BCS")
Rws = .Cells(Rows.Count, "A").End(xlUp).Row
Set Rng = Range(.Cells(2, 1), .Cells(Rws, 7)) 'Column a to column G
Rng.Copy Wb.Worksheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
ActiveWorkbook.Close True
End With
MyFile = Dir()
Loop
End Sub
Thank you so much for your help

VBA - Loop through files in a folder AND copy single cells as well as a range, if condition is met

I am currently using a piece of code to loop through files in a folder and copy certain cells from each file into a master list. There are a number of files being added into the folder every week. One of the columns in the master list includes the filenames of previously looped files. The code only loops through files that are not included in the filename list and therefore also have not previously been looped.
The code works really well and copies cells with satisfactory results however I now need to modify it to also copy a range of data (A20:H33 specifically) as well as meeting the above condition of not already being looped.
I have tried the following unsuccesfully:
Adding another varTemp to the code (As seen in the main code)
Adding a sub that can copy a range (However I have been unable to incorporate this into the code so it satisfies the not looped condition)
Using selection.copy and selection.paste however an error that I cannot workaround pops up ("Object doesn't support this property or method")
Here is the main code:
Option Explicit
Sub CopyFromFolderExample()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets(1)
Dim strFolder As String, strFile As String, r As Long, wb As Workbook
Dim varTemp(1 To 6) As Variant
Application.ScreenUpdating = False
strFolder = "D:\Other\folder\"
r = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
strFile = Dir(strFolder & "*.xl*")
Do While Len(strFile) > 0
If Not Looped(strFile, ws) Then
Application.StatusBar = "Reading data from " & strFile & "..."
Set wb = Workbooks.Add(strFolder & strFile)
With wb.Worksheets(1)
varTemp(1) = strFile
varTemp(2) = .Range("A13").Value
varTemp(3) = .Range("H8").Value
varTemp(4) = .Range("H9").Value
varTemp(5) = .Range("H37").Value
'varTemp(6) = .Range("A20:H33").Value
End With
wb.Close False
r = r + 1
ws.Range(ws.Cells(r, 1), ws.Cells(r, 6)).Formula = varTemp
End If
strFile = Dir
Loop
Application.StatusBar = False
Application.ScreenUpdating = True
End Sub
Private Function Looped(strFile As String, ws As Worksheet) As Boolean
Dim Found As Range
Set Found = ws.Range("A:A").Find(strFile)
If Found Is Nothing Then
Looped = False
Else
Looped = True
End If
End Function
This is the snippet of code that when inserted into the main code just below tha last vartemp gives me the following error ("Object doesn't support this property or method")
.Range("A20:H33").Select
.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ws.Activate
If ws.Range("A1") = "" Then
ws.Range("A1").Select
Selection.Paste
Else
Selection.End(xlDown).Offset(6, 0).Select
Selection.Paste
End If
Here is what I am trying to achieve:
I think that if you use a Range variable instead of a Variant to copy and paste the Range(A20:AH33) should get the job done.
Declare:
Dim rg as Range
Then replace this line of code:
varTemp(6) = .Range("A20:H33").Value
For this:
Set rg = .Range("A20:H33")
Then you can just Rg.Copy and paste whereaver you want.
Don't forget to "clear" the copybuffer after you paste the information:
Application.CutCopyMode = False
Avoid to use Selectionand Activate in your code, the reasons for it can be seen here:
How to avoid using Select in Excel VBA
and here:
https://www.businessprogrammer.com/power-excel-vba-secret-avoid-using-select/
This should do it. I've turned your array back to 5 elements, and the range is transferred separately. I've added a few new variables which you might want to give more meaningful names.
Sub CopyFromFolderExample()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets(1)
Dim strFolder As String, strFile As String, r As Long, wb As Workbook
Dim varTemp(1 To 5) As Variant, r1 As Long, r3 As Range
Application.ScreenUpdating = False
strFolder = "D:\Other\folder\"
strFile = Dir(strFolder & "*.xl*")
Do While Len(strFile) > 0
If Not Looped(strFile, ws) Then
Application.StatusBar = "Reading data from " & strFile & "..."
Set wb = Workbooks.Add(strFolder & strFile)
With wb.Worksheets(1)
varTemp(1) = strFile
varTemp(2) = .Range("A13").Value
varTemp(3) = .Range("H8").Value
varTemp(4) = .Range("H9").Value
varTemp(5) = .Range("H37").Value
Set r3 = .Range("A20:H33")
End With
With ws
r = .Range("A" & .Rows.Count).End(xlUp).Row + 1
r1 = .Range("F" & .Rows.Count).End(xlUp).Row + 1 'last used row in col F
.Range(.Cells(r, 1), .Cells(r, 5)).Value = varTemp
.Cells(r1, 6).Resize(r3.Rows.Count, r3.Columns.Count).Value = r3.Value 'transfer A20:H33
End With
wb.Close False
End If
strFile = Dir
Loop
Application.StatusBar = False
Application.ScreenUpdating = True
End Sub

Resources