Trying to create a Loop - excel

I am trying to create a loop
That the A1:AZ1 data should be copied across all sheets and pastespecial just values into new sheet.
Sub CombineData()
Dim I As Long
Dim xRg As Range
On Error Resume Next
Worksheets.Add Sheets(1)
ActiveSheet.Name = "Count"
For I = 2 To Sheets.Count
Set xRg = Sheet1.Range("A1:AZ1")
If I > 2 Then
Set xRg = Sheets(1).Cells(xRg.Rows.Count + 1, 1)
End If
Sheets(I).Activate
ActiveSheet.Range("A1:AZ1").Copy
Next
End Sub
FaneDuru Yes you are right and my comment limit has stoped

Try the next way, please. Now, it adds a new sheet and copy in it, on consecutive rows, the content of "A1:AZ1" range (as value) for all existing worksheets. Is this what you need?
Sub CopyRangeFromAllSheets()
Dim sh As Worksheet, ws As Worksheet, arr As Variant, lastEmptyR As Long
Set sh = Sheets.aDD: sh.Name = "Count"
For Each ws In ActiveWorkbook.Worksheets
If ws.Name <> sh.Name Then
arr = ws.Range("A1:AZ1").Value
lastEmptyR = sh.Range("A" & Rows.count).End(xlUp).row
sh.Range("A" & lastEmptyR & ":AZ" & lastEmptyR).Value = arr
End If
Next
End Sub
Edited by #Shoaib Ali not being able to post comments:
Yeah its working fine thanks and my comments limit is stopped

Related

Add data in listbox in multiple columns

recently i came across a userfrom which have list box which shows the sheets name in first column and there property like are they visible or hidden in second columns. but when i tried to access the codes its lock i googled and did every thing to understand how it is done but i didnt found it hope i get my answer here below is mycode which i did i am noob please help me
my code:-
Private Sub UserForm_Initialize()
Dim ws As Worksheet
ListBox1.ColumnCount = 2
For Each ws In ThisWorkbook.Worksheets
Me.ListBox1.AddItem ws.Name
Next ws
End Sub
Private Sub UserForm_Initialize()
Dim ws As Worksheet, n As Long, arText
arText = Array("xlSheetVisible", "xlSheetHidden", "", "xlSheetVeryHidden")
ListBox1.ColumnCount = 2
For Each ws In ThisWorkbook.Worksheets
Me.ListBox1.AddItem ws.Name
Me.ListBox1.List(n, 1) = arText(ws.Visible + 1)
n = n + 1
Next ws
End Sub
There are several possibilities. One of them is:
Sub ListBoxMitArrayAusTabelleFuellen()
Dim VarDat As Variant
Dim lngRowMax As Long
With Tabelle1
lngRowMax = .Range("A" & .Rows.Count).End(xlUp).Row
VarDat = .Range("A2:B" & lngRowMax ).Value
.ListBox1.ColumnCount = UBound(VarDat, 2)
.ListBox1.Clear
.ListBox1.List = VarDat
End With
End Sub
BG
Bernd

Copy Row from every sheet with cell containing word

I am building out a workbook where every sheet is for a different stage of a software installation. I am trying to aggregate the steps that fail by copying my fail rows into a summary sheet. I finally got them to pull, but they are pulling into the new sheet on the same row # as they are located in the original sheet.
Here is what I am using now:
Option Explicit
Sub Test()
Dim Cell As Range
With Sheets(7)
' loop column H untill last cell with value (not entire column)
For Each Cell In .Range("D1:D" & .Cells(.Rows.Count, "D").End(xlUp).Row)
If Cell.Value = "Fail" Then
' Copy>>Paste in 1-line (no need to use Select)
.Rows(Cell.Row).Copy Destination:=Sheets(2).Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
End If
Next Cell
End With
End Sub
I need to:
Pull row that has cell containing "Fail"
Copy row into master starting at Row 4 and consecutively down without overwriting
Run across all sheets at once-
*(they are named per step of install - do i need to rename to "sheet1, sheet2, etc"????)
When macro is run clear previous results (to avoid duplicity)
Another user offered me an autofilter macro but it is failing on a 1004 at this line ".AutoFilter 4, "Fail""
Sub Filterfail()
Dim ws As Worksheet, sh As Worksheet
Set sh = Sheets("Master")
Application.ScreenUpdating = False
'sh.UsedRange.Offset(1).Clear 'If required, this line will clear the Master sheet with each transfer of data.
For Each ws In Worksheets
If ws.Name <> "Master" Then
With ws.[A1].CurrentRegion
.AutoFilter 4, "Fail"
.Offset(1).EntireRow.Copy sh.Range("A" & Rows.Count).End(3)(2)
.AutoFilter
End With
End If
Next ws
Application.ScreenUpdating = True
End Sub
Try this:
The text “Completed” in this xRStr = "Completed" script indicates the specific condition that you want to copy rows based on;
C:C in this Set xRg = xWs.Range("C:C") script indicates the specific column where the condition locates.
Public Sub CopyRows()
Dim xWs As Worksheet
Dim xCWs As Worksheet
Dim xRg As Range
Dim xStrName As String
Dim xRStr As String
Dim xRRg As Range
Dim xC As Integer
On Error Resume Next
Application.DisplayAlerts = False
xStr = "New Sheet"
xRStr = "Completed"
Set xCWs = ActiveWorkbook.Worksheets.Item(xStr)
If Not xCWs Is Nothing Then
xCWs.Delete
End If
Set xCWs = ActiveWorkbook.Worksheets.Add
xCWs.Name = xStr
xC = 1
For Each xWs In ActiveWorkbook.Worksheets
If xWs.Name <> xStr Then
Set xRg = xWs.Range("C:C")
Set xRg = Intersect(xRg, xWs.UsedRange)
For Each xRRg In xRg
If xRRg.Value = xRStr Then
xRRg.EntireRow.Copy
xCWs.Cells(xC, 1).PasteSpecial xlPasteValuesAndNumberFormats
xC = xC + 1
End If
Next xRRg
End If
Next xWs
Application.DisplayAlerts = True
End Sub
Here's another way - You'll have to assign your own Sheets - I used 1 & 2 not 2 & 7
Sub Test()
Dim xRow As Range, xCel As Range, dPtr As Long
Dim sSht As Worksheet, dSht As Worksheet
' Assign Source & Destination Sheets - Change to suit yourself
Set sSht = Sheets(2)
Set dSht = Sheets(1)
' Done
dPtr = Sheets(1).Rows.Count
dPtr = Sheets(1).Range("D" & dPtr).End(xlUp).Row
For Each xRow In sSht.UsedRange.Rows
Set xCel = xRow.Cells(1, 1) ' xCel is First Column in Used Range (May not be D)
Set xCel = xCel.Offset(0, 4 - xCel.Column) ' Ensures xCel is in Column D
If xCel.Value = "Fail" Then
dPtr = dPtr + 1
sSht.Rows(xCel.Row).Copy Destination:=dSht.Rows(dPtr)
End If
Next xRow
End Sub
I think one of the problems in your own code relates to this line
.Rows(Cell.Row).Copy Destination:=Sheets(2).Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
The section Rows.Count, "A" should be referring to the destination sheet(2) but isn't because of the line
With Sheets(7)
further up

VBA Macro that removes duplicates based on column names

I am very new to Excel VBA I made this macro to remove duplicates based on column name "container". Now there are 2 columns in excel with the name "Container".
Sub Remove_DupContainerPOL()
'Removes Duplicate Containers
Dim whs As Worksheet
Dim lRow As Long, colNumber As Long
Dim colh As String
colh = "Container"
lRow = Range("A1").End(xlDown).Row
Set whs = Worksheets("POL")
colNumber = Application.Match(colh, whs.Range("A1:AAA1"), 0)
With whs.Range("A1:AAA" & lRow)
.RemoveDuplicates Columns:=colNumber, Header:=xlYes
End With
End Sub
Original Excel File
This is how the columns look like in the excel file. Now when I execute the macro it misbehaves somehow not sure the entire data in preceding rows get shuffled and generates the wrong output.
Is there any way that macro reads the 3 columns i.e. "Container" and only based on that removes duplicates?
Further, I am adding an explanation in detail.
Tab named Ocean which has 2 columns named Container! I coded in a way that the data in this ocean creates 2 new tabs named POL and POD and in that POL and POD tab I want to remove the duplicates based on the column named “Container” which is creating the wrong output.
Main Ocean tab where duplicate data.
POL Tab where Macro shuffled the data and gave wrong output
My complete macro codes below:
Sub Split_Ocean()
'------------------------------Filter on column Mode and split all Ocean moves into newsheet--------------------------
Application.AskToUpdateLinks = False
Dim wb As Workbook
' If the code is in the ActiveWorkbook you should use ThisWorkbook instead.
Set wb = ActiveWorkbook
' Delete Target Worksheet.
Dim FSht As Worksheet
On Error Resume Next
Set FSht = wb.Worksheets("Ocean")
If Err.Number = 0 Then
Application.DisplayAlerts = False
FSht.Delete
Application.DisplayAlerts = True
End If
On Error GoTo 0
' Define Target Worksheet.
Set FSht = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))
FSht.Name = "Ocean"
' Define Source Worksheet.
Dim Tsht As Worksheet
Set Tsht = wb.Worksheets("Main")
With Tsht
If Tsht.AutoFilterMode Then
Tsht.AutoFilterMode = False
End If
' 14 is column N
.Range("A1").AutoFilter Field:=14, Criteria1:="Ocean"
.AutoFilter.Range.Copy FSht.Range("A1")
End With
'-------------------------------------------------Endforabovecode---------------------
'Wait for 3 sec
Application.Wait (Now + TimeValue("0:00:03"))
'Create POL
Dim Source As Worksheet
Dim Destination As Worksheet
'Checking whether "POL" sheet already exists in the workbook
For Each Source In ThisWorkbook.Worksheets
If Source.Name = "POL" Then
MsgBox "POL sheet already exist"
Exit Sub
End If
Next
ActiveWorkbook.Worksheets("Ocean").Copy After:=Worksheets(Sheets.Count)
On Error Resume Next
ActiveSheet.Name = "POL"
'Autofit all contents in POL
ActiveWorkbook.Worksheets("POL").UsedRange.Columns.AutoFit
'Create POD & check whether "POD" sheet already exists in the workbook
For Each Source In ThisWorkbook.Worksheets
If Source.Name = "POD" Then
MsgBox "POD sheet already exist"
Exit Sub
End If
Next
ActiveWorkbook.Worksheets("Ocean").Copy After:=Worksheets(Sheets.Count)
On Error Resume Next
ActiveSheet.Name = "POD"
'Autofit all contents in POD
ActiveWorkbook.Worksheets("POD").UsedRange.Columns.AutoFit
Application.Wait (Now + TimeValue("0:00:02"))
ActiveWorkbook.Worksheets("Main").AutoFilterMode = False
End Sub
Sub Remove_DupContainerPOL()
'Removes Duplicate Containers
Dim whs As Worksheet
Dim lRow As Long, colNumber As Long
Dim colh As String
colh = "Container"
lRow = Range("A1").End(xlDown).Row
Set whs = Worksheets("POL")
colNumber = Application.Match(colh, whs.Range("A1:E1"), 0)
With whs.Range("A1:E1" & lRow)
.RemoveDuplicates Columns:=colNumber, Header:=xlYes
End With
End Sub
Sub Remove_DupContainerPOD()
'Removes Duplicate Containers
Dim whs As Worksheet
Dim lRow As Long, colNumber As Long
Dim colh As String
colh = "Container"
lRow = Range("A1").End(xlDown).Row
Set whs = Worksheets("POD")
colNumber = Application.Match(colh, whs.Range("A1:E1"), 0)
With whs.Range("A1:E1" & lRow)
.RemoveDuplicates Columns:=colNumber, Header:=xlYes
End With
End Sub
Main Ocean tab where duplicate data.
POL Tab where Macro shuffled the data and gave wrong output
With whs.Range("A1:E1" & lRow) .RemoveDuplicates should be With whs.Range("A1:N" & lRow) to cover all the columns (assuming N is last column). Or maybe just use With whs.UsedRange.

Copy and paste data from one sheet to multiple where range matches sheet names

I have an API call that pulls data relating to 34 individual sites. Each site has a varying number of assets within it, each with a unique identifier.
I am trying to write a macro that will copy and paste the data for specific sites into their own individual worksheet within the file. The basic concept of this I am familiar with but I am struggling with the ranges I need to specify.
So basically, I need the macro to work its way down Column A of the sheet called Raw Data and identify any rows where the Site name (Value in column A) matches one of the Sheet names. It should then copy the Rows from A to H with that site name and paste into the respective site sheet in rows A to H.
The values in Column A will always match one of the other sheets in the workbook.
Example image that might help explain a bit better:
Apologies in advance if my explanation is not very clear. I have very limited experience using macros so I am not sure if my way of explaining what I want to achieve is understandable or if at all possible.
I am very keen to learn however and any guidance you fine folk could offer would be very much appreciated.
Welcome!
Try this one
Function ChkSheet(SheetName As String) As Boolean
For i = 1 To Worksheets.Count
If Worksheets(i).Name = SheetName Then
ChkSheet = True
Exit Function
End If
Next
ChkSheet = False
End Function
Sub test()
Dim i, j, k As Long
Dim wsRaw As Worksheet
Dim Aux As String
Set wsRaw = Worksheets("Raw Data")
For i = 1 To wsRaw.Range("A:A").SpecialCells(xlCellTypeLastCell).Row
If ChkSheet(wsRaw.Cells(i, 1).Value2) Then
Aux = wsRaw.Cells(i, 1).Value2
k = Worksheets(Aux).Range("A:A").SpecialCells(xlCellTypeLastCell).Row + 1
For j = 1 To 8
Worksheets(Aux).Cells(i + k, j).Value2 = wsRaw.Cells(i, j).Value2
Next
Else
Worksheets.Add.Name = wsRaw.Cells(i, 1).Value2
Aux = wsRaw.Cells(i, 1).Value2
k = 2
For j = 1 To 8
Worksheets(Aux).Cells(i + k, j).Value2 = wsRaw.Cells(i, j).Value2
Next
End If
Next
End Sub
So the Function ChkSheet will check if the sheet exist (you don´t need to create them) and the procedure test will follow all the items that you have in your "Raw Data" worksheet and it will copy to the last used row of every sheet.
And please, even for a newbie, google, read, get some information and when you get stacked, ask for help. This forum is not for giving solutions with not effort.
Good morning all,
David, thanks very much for your help with this. I really didn't want you to think I was trying to get someone to give me the answer and I had tried a few other things before asking the question, but I neglected to show any evidence of my workings. Rookie mistake and I apologise for this.
Having done a bit more research online and with a good dollop of help from a much more experienced colleague I have got the below code using advance filter which works perfectly for what I need.
I thought I would share it here in case it is of any use to others in the future.
Option Explicit
Dim RawDataCol As String
Dim ListCol As String
Dim AdvRng As String
Dim RawDataRng As String
Dim SiteAbrRng As String
Dim ShiftCols As String
Private Sub SetParameters()
'Cell Address where RawData is pasted to each of the site sheets
RawDataCol = "A2"
'Column where the Unique List is cleared and pasted
ListCol = "L"
'Advanced Filter Range
AdvRng = "A1:K2"
'Pasted Raw Data Columns on each sheet
RawDataRng = "A2:K"
'Site Abr gets pasted to the address during loop
SiteAbrRng = "A2"
'Range that gets deleted after pasting Raw Data to each sheet
ShiftCols = "A2:K2"
End Sub
Sub CopyDataToSheets()
On Error GoTo ErrorHandler
AppSettings (True)
Dim StartTime As Double
Dim SecondsElapsed As Double
StartTime = Timer
Dim wbk As Workbook
Dim sht_RawData As Worksheet, sht_target As Worksheet, sht_AdvancedFilter As Worksheet, sht_TurbineData As Worksheet
Dim tbl_RawData As ListObject
Dim LastRow1 As Long, LastRow2 As Long, UniqueListCount As Long
Dim MyArr As Variant
Dim ArrTest As Boolean
Dim x As Long, AdvRowNo As Long
Set wbk = ThisWorkbook
SetParameters
Set sht_RawData = wbk.Worksheets("Raw Data")
Set sht_AdvancedFilter = wbk.Worksheets("Advanced Filter")
Set sht_TurbineData = wbk.Worksheets("Turbine Data")
Set tbl_RawData = sht_RawData.ListObjects("_00")
'clear unqie list of SiteAbr
With sht_TurbineData
LastRow1 = .Cells(Rows.Count, 12).End(xlUp).Row
If LastRow1 > 1 Then
'sht_TurbineData.Range("L1:L" & LastRow1).ClearContents
sht_TurbineData.Range(ListCol & 1 & ":" & ListCol & LastRow1).ClearContents
End If
End With
'Copy Unqiue list of SiteAbr to Turbie Data Sheet
tbl_RawData.Range.Columns(1).AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=sht_TurbineData.Range(ListCol & 1), _
Unique:=True
LastRow1 = sht_TurbineData.Cells(Rows.Count, sht_TurbineData.Range(ListCol & 1).Column).End(xlUp).Row
'Sort Unique List
sht_TurbineData.Range("L1:L" & LastRow1).Sort _
Key1:=sht_TurbineData.Range("L1"), _
Order1:=xlAscending, _
Header:=xlYes
'Load unique site Abr to array
With sht_TurbineData
'MyArr = Application.Transpose(.Range("L2:L" & LastRow1))
MyArr = Application.Transpose(.Range(ListCol & 2 & ":" & ListCol & LastRow1))
UniqueListCount = LastRow1 - 1
End With
'Test Array conditions for 0 items or 1 item
ArrTest = IsArray(MyArr)
If UniqueListCount = 1 Then
MyArr = Array(MyArr)
ElseIf UniqueListCount = 0 Then
GoTo ExitSub
End If
For x = LBound(MyArr) To UBound(MyArr)
Set sht_target = wbk.Worksheets(MyArr(x))
With sht_target
'Find the last non blank row of the target paste sheet
LastRow2 = .Cells(Rows.Count, 1).End(xlUp).Row
'Clear contents if the Last Row is not the header row
If LastRow2 > 1 Then
.Range(RawDataRng & LastRow2).ClearContents
End If
sht_AdvancedFilter.Range(SiteAbrRng) = MyArr(x)
'Filter Source Data and Copy to Target Sheet
tbl_RawData.Range.AdvancedFilter _
Action:=xlFilterCopy, _
CriteriaRange:=sht_AdvancedFilter.Range(AdvRng), _
CopyToRange:=.Range(RawDataCol), _
Unique:=False
'Remove the first row as this contains the headers
.Range(ShiftCols).Delete xlShiftUp
End With
Next x
ExitSub:
SecondsElapsed = Round(Timer - StartTime, 3)
AppSettings (False)
'Notify user in seconds
MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation
Exit Sub
ErrorHandler:
MsgBox (Err.Number & vbNewLine & Err.Description)
GoTo ExitSub
End Sub
Sub ClearAllSheets()
Dim tbl_SiteList As ListObject
Dim wbk As Workbook
Dim sht_target As Worksheet, sht_TurbineData As Worksheet
Dim MyArray As Variant
Dim x As Long, LastRow As Long
Set wbk = ThisWorkbook
Set sht_TurbineData = wbk.Worksheets("Turbine Data")
Set tbl_SiteList = sht_TurbineData.ListObjects("SiteList")
SetParameters
MyArray = Application.Transpose(tbl_SiteList.DataBodyRange)
For x = LBound(MyArray) To UBound(MyArray)
Set sht_target = wbk.Worksheets(MyArray(x))
LastRow = sht_target.Cells(Rows.Count, 1).End(xlUp).Row
If LastRow > 1 Then
sht_target.Range("A2:K" & LastRow).ClearContents
End If
Next x
End Sub
Private Sub AppSettings(Opt As Boolean)
If Opt = True Then
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
ElseIf Opt = False Then
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End If
End Sub
Thanks again to all who answered and especially to you David. Although I have only used the basic principles from what you offered, it was extremely useful to help me understand what I needed to do in order to get the data to copy into the correct sheets.
Many thanks,
MrChrisP

Copy specific sheet names from range

I need help and I'm hoping someone here can help me :)
I have a workbook that runs some reports from Avaya CMS. It runs the report and creates a new sheet for each persons name on the MAIN sheet. << This part works wonderfully.
My issue is I cannot figure out how to use that range of names on the MAIN sheet to select only those specific sheets and then copy them to a new workbook.. There's 2 other hidden sheets as well.. Which is why I think using the range of names is easier but I'm open to anything at this point.
Here's an screeshot of what it looks like :
Sorry, I couldn't figure out how to upload the workbook here but the image should, hopefully, be good enough. Thank you for your time and help!
Here's an image with the hidden sheets.
I need it to exclude the first 3 sheets/
And here's the code:
Sub Macro1()
Dim sheetArray() As String
Dim i As Integer
i = 0
For Each c In MainSheet.Range("A2:A20").Cells
ReDim Preserve sheetArray(0 To i)
sheetArray(i) = c.Value
i = i + 1
Next
Sheets(sheetArray).Select
End Sub
Sub move_Sheets()
Dim mSH As Worksheet
Set mSH = ThisWorkbook.Sheets("Main")
Dim shArray() As String
Dim i As Integer
i = mSH.Range("A" & Rows.Count).End(xlUp).Row
ReDim Preserve shArray(0 To i - 2)
For a = 2 To i
shArray(a - 2) = mSH.Range("A" & a).Value
Next a
ThisWorkbook.Sheets(shArray).Move
End Sub
You could try:
Option Explicit
Sub test()
Dim LastRow As Long, i As Long, sheetIndex As Long
Dim SheetName As String
Dim ws As Worksheet
With ThisWorkbook.Worksheets("Main")
'Last row of column where the names appears
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
'Loop the column from row 2 to last row
For i = 2 To LastRow
'Set Sheet name
SheetName = .Range("A" & i).Value
'Check if the sheet with the SheetName exists
If DoesSheetExists(SheetName) Then
'Insert the code to code
sheetIndex = Workbooks("Book2").Sheets.Count
ThisWorkbook.Worksheets(SheetName).Copy After:=Workbooks("Book2").Sheets(sheetIndex)
Else
End If
Next i
End With
End Sub
Function DoesSheetExists(SheetName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = ThisWorkbook.Sheets(SheetName)
On Error GoTo 0
If Not ws Is Nothing Then DoesSheetExists = True
End Function

Resources