Code at the bottom
Hi, I just got this macro to repair. People tell me that it was working before.
This macro is supposed to copy only the visible filtered data (dynamic tables mainly) and create a new excel file with all the same worksheets but with only the visible data copied and paste in them (worksheets) with no dynamic table. This is meant to reduce the weight of the file but not to make an exact copy.
You are supposed to open this file with the one you want to transfer data and you run the macro in the files you want to copy.
First there were methods errors with 'Sheets(Pages).Select' (I switched from .Activate) and it worked.
After that 'NewBook.Sheets(1).Range("A1:BZ500").Select' were methods errors for range, so I split it in two lines:
'NewBook.Sheets(1).activate'
'Range("A1:BZ500").Select'
This resolved that error.
After that, there is a name attribution error (like the name is already used) to the line:
NewBook.Sheets(1).Name = OldBook.Sheets(Page).Name ( i tried a spy but ieverything was ok) so I decided to write it like NewBook.Sheets(1).Name = OldBook.Sheets(Page).Name + Cstr(Page)
It resolved the error but the macro is still not doing what it's meant to:
Set OldBook = ActiveWorkbook
Set NewBook = Workbooks.Add
NewBook.Worksheets(1).Name = "Vide"
OldBook.Activate
For Page = 1 To Sheets.Count - 1
OldBook.Activate
Sheets(Page).Activate
Sheets(Page).Copy Before:=NewBook.Sheets(1)
NewBook.Activate
NewBook.Sheets(1).Name = OldBook.Sheets(Page).Name
NewBook.Sheets(1).Range("A1:BZ500").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Next
End Sub
Below is the one with my corrections:
Sub Fichier_Plat()
Code_optimizer (True)
Set OldBook = ActiveWorkbook
Set NewBook = Workbooks.Add
NewBook.Worksheets(1).Name = "Vide"
OldBook.Activate
For Page = 1 To Sheets.Count - 1
OldBook.Activate
Sheets(Page).Activate
Sheets(Page).Copy Before:=NewBook.Sheets(1)
NewBook.Activate
NewBook.Sheets(1).Name = OldBook.Sheets(Page).Name + CStr(Page)
NewBook.Sheets(1).Activate
Range("A1:BZ500").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Next
Code_optimizer (False)
End Sub
I'd start by giving the original coder a hard slap for not defining the variables/not having 'Option Explicit' at the top of the module, for using Select and Activate and for hard-coding the range that's to be copied.
Maybe this code would be better?
Public Sub Fichier_Plat()
Dim OldBook As Workbook 'Declare your variables!
Set OldBook = ActiveWorkbook
Dim NewBook As Workbook
Set NewBook = Workbooks.Add(xlWBATWorksheet) 'Create new workbook with a single sheet.
NewBook.Worksheets(1).Name = "Vide"
Dim wrkSht As Worksheet
Dim newwrksht As Worksheet
For Each wrkSht In OldBook.Worksheets 'Look at each sheet in turn.
Set newwrksht = NewBook.Worksheets.Add
With newwrksht
.Name = wrkSht.Name 'Will cause error if one of them is called "Vide". Can use wrksht.Index to get number of sheet.
wrkSht.Range(wrkSht.Cells(1, 1), LastCell(wrkSht)).Copy
.Range("A1").PasteSpecial xlPasteValues
.Range("A1").PasteSpecial xlPasteFormats
End With
Next wrkSht
End Sub
Public Function LastCell(wrkSht As Worksheet) As Range
Dim LastCol As Long, LastRow As Long
On Error Resume Next
With wrkSht
LastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
LastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row
End With
If LastCol = 0 Then LastCol = 1
If LastRow = 0 Then LastRow = 1
Set LastCell = wrkSht.Cells(LastRow, LastCol)
End Function
Related
I get workbooks with multiple tabs of identically formatted data but the exact ranges of the data varies between workbooks. Instead of modifying the code each time, I am trying to establish a user input that would define a reference range on one worksheet that can be applied to all the worksheets. My problem is that the defined range keeps referring back to my "reference" range and not applying to the active worksheet. I am ending up with the same data being copied repeatedly.
Sub Copy_data()
Dim Destination_Rng As Range
Dim Header_Rng As Range
Dim Data_Rng As Range
Dim Label_Rng As Range
Dim ws As Worksheet
Dim SheetName As String
Dim SheetExists As Boolean
On Error Resume Next
SheetName = InputBox("Please enter a name for your new sheet")
SheetExists = False
With ThisWorkbook
'Check if the Sheet exists
For Each ws In .Worksheets
If ws.Name = SheetName Then
SheetExists = True
MsgBox ("Summary tab already exists - Ending Script")
Exit Sub
End If
Next
If SheetExists = False Then
'If the sheet dont exists, create
.Worksheets.Add Sheets(1)
ActiveSheet.Name = SheetName
End If
End With
Sheets(2).Activate
'Get user input for data header
Set Header_Rng = Application.InputBox("Select by mouse or enter (e.g. A1:B2) the Header Data:", Type:=8)
'Get user input for data to be compiled
Set Data_Rng = Application.InputBox("Select by mouse or enter (e.g. A1:B2) the Data to be compiled:", Type:=8)
'Get user input for data label
Set Label_Rng = Application.InputBox("Select by mouse or enter (e.g. A1:B2) the data label:", Type:=8)
On Error GoTo 0
'Test to ensure User Did not cancel
If Header_Rng Is Nothing Then Exit Sub
If Data_Rng Is Nothing Then Exit Sub
If Label_Rng Is Nothing Then Exit Sub
Header_Rng.Copy
Sheets(SheetName).Activate
Range("B1").PasteSpecial
'sometimes the header is formatted weird so adding a value between header and data
Sheets(SheetName).Range("B" & Rows.Count).End(xlUp).Offset(1, 0).Select
Selection.Value = "X"
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> SheetName Then
Data_Rng.Copy
Sheets(SheetName).Activate
Set Destination_Rng = Sheets(SheetName).Range("B" & Rows.Count).End(xlUp).Offset(1, 0)
Destination_Rng.Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Label_Rng.Cells(1, 1).Copy
Sheets(SheetName).Activate
Destination_Rng.Offset(0, -1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
Next ws
End Sub
i want a macro to add a new sheet and use it to paste some tables, but i when i run the macro again i wanna use the same newly created sheet and not to add a new sheet everytime i run the macro. Can u help me?
I am using the code that folows:
Sub cria_relatorio()
Dim newS As Worksheet, currentS As Worksheet
Dim aba_anterior As Worksheet
lugarAnterior = Selection.Address
Set pos = ActiveSheet
Set currentWB = ThisWorkbook
Set currentS = currentWB.Sheets("fim")
currentS.Range("PRODUTOS").Select 'table that i wanna copy and paste(it changes the values)
Selection.Copy
Sheets("tabelas_por_produto").Activate
ActiveCell.End(xlUp).Offset(1, 0).Select
Range("A1").Activate
If ActiveCell.Value = "" Then
ElseIf Range("a1000").End(xlUp).Offset(2, 0) = "" Then
Range("a1000").End(xlUp).Offset(2, 0).Select
Else
Selection.End(xlDown).Select
ActiveCell.Offset(2, 0).Select
End If
ActiveCell.PasteSpecial _
Paste:=xlPasteValues, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=False
ActiveCell.PasteSpecial _
Paste:=xlPasteFormats, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=False
ActiveCell.PasteSpecial _
Paste:=xlPasteColumnWidths, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=False
Rows("1:200").AutoFit
End Sub
Copy Versions of a Range One Below the Other
Copy the code into a standard module (e.g. Module1).
Carefully adjust the constants and the workbook if necessary.
It is assumed that PRODUTO is a defined
name of
a range, with workbook scope.
The Code
Option Explicit
Sub cria_relatorio()
' Define constants.
Const srcName As String = "fim"
Const tgtName As String = "tabelas_por_produto"
Const rngName As String = "PRODUTOS"
Const tgtFirst As String = "A1"
Const tgtOffset As Long = 2
Dim wb As Workbook: Set wb = ThisWorkbook
' Define Source Range.
Dim src As Range: Set src = wb.Names(rngName).RefersToRange
' Define Target worksheet.
Dim ws As Worksheet
On Error Resume Next
Set ws = wb.Worksheets(tgtName): GoSub NoWorksheet
On Error GoTo 0
' Define Target Cell.
Dim tgt As Range
Set tgt = ws.Columns(ws.Range(tgtFirst).Column) _
.Find("*", , xlValues, , , xlPrevious)
If tgt Is Nothing Then Set tgt = ws.Range(tgtFirst)
If tgt.Row < ws.Range(tgtFirst).Row Then Set tgt = ws.Range(tgtFirst)
Set tgt = tgt.Offset(tgtOffset)
' Do copy/paste.
src.Copy
With tgt.Resize(src.Rows.Count, src.Columns.Count)
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
.PasteSpecial xlPasteColumnWidths
.Rows.AutoFit
End With
Exit Sub
NoWorksheet:
If Err.Number <> 0 Then
wb.Worksheets.Add
Set ws = ActiveSheet: ws.Name = tgtName
End If
Return
End Sub
I made this simple code, or at least tried. But I have one small problem.
When I type For I = 14 To 25 I don't really know what I'm doing. I have a sheet called "Master" and in the range K6:V6 I have every name of every sheet I want to go through. I would like to write something like this: For I = sheets("Master").range("K6:V6") But this does not work, anyone that can help to me to assign the "names" in this array to I?
The rest of the code works as it should, it could be optimized by not having "select" but I don't seem to be able to do it so I took the easy way out. Thank you for your help!
Dim I As Integer
For I = 14 To 25
If Sheets(I).Visible = False Then
'If sheet = Not visble
'-----------------------------------------------------------------------------------------------------
Sheets(I).Visible = True
AA = Sheets("Master").Range("K6").Value
Sheets(AA).Select
ActiveSheet.Unprotect
ActiveSheet.Range("C3:C120").Copy
Range("G3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveSheet.Range("C6:C120").ClearContents
ActiveSheet.Range("L6:M117").ClearContents
ActiveSheet.Protect
Range("A1").Select
Sheets(I).Visible = False
'-----------------------------------------------------------------------------------------------------
Else:
'If sheet = visble
'-----------------------------------------------------------------------------------------------------
AA = Sheets("Master").Range("K6").Value
Sheets(AA).Select
ActiveSheet.Unprotect
ActiveSheet.Range("C3:C120").Copy
Range("G3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveSheet.Range("C6:C120").ClearContents
ActiveSheet.Range("L6:M117").ClearContents
ActiveSheet.Protect
Range("A1").Select
'-----------------------------------------------------------------------------------------------------
End If
Next I
Each Worksheet in a file is held in the Worksheets collection. You can look at each worksheet in the collection in turn and act on it.
Sub Test()
Dim wrkSht As Worksheet
Dim shtMaster As Worksheet
Dim InList As Range
Dim VisibleSetting As Long
Set shtMaster = ThisWorkbook.Worksheets("Master") 'Reference to Master worksheet
'This will look at each worksheet in the worksheets collection and reference it with 'wrkSht'
For Each wrkSht In ThisWorkbook.Worksheets
'Look for the worksheet name in the K6:V6 range.
Set InList = shtMaster.Range("K6:V6").Find(wrkSht.Name, LookIn:=xlValues, LookAt:=xlWhole)
'If the name is found InList will not be nothing.
If Not InList Is Nothing Then
With wrkSht
VisibleSetting = .Visible 'Remember the visible setting.
.Visible = xlSheetVisible
.Unprotect
.Range("C3:C120").Copy
.Range("G3").PasteSpecial xlPasteValues
Union(.Range("C3:C120"), .Range("L6:M17")).ClearContents
.Visible = VisibleSetting 'Put the visible setting back.
.Protect
End With
End If
Next wrkSht
End Sub
Further reading:
ThisWorkbook
With...End With Statement
For Each...Next Statement
I have a Master workbook (Consolidate Tracker) where we add data from Source file.
Consolidated Tracker and Source file have three tabs (Open Positions, Closed, Cancelled).
Every week I put data from Source file (from each tab) into the Consolidated file (to each tab).
For example: Open Positions data from Source file goes to Open Positions in Consolidated Tracker and so on.
I am facing the following issues:
I have to give full name of the files.
For example. Workbooks("Source*") is not working.
Is there a way to give only partial names?
My file name will have a date in the end. Hence I want to give *.
ActiveWorkbook.Sheets(I) or ActiveWorkbook.Sheets("Name") always goes for the Open Worksheet/Tab.
Pasting the output gives the following error.
Method PasteSpecial of Object Range Failed
Selection.EntireRow.Delete sometimes gives error or sometimes
doesn’t delete and again goes into For loop.
Also, it seems the loop is not taking the next tab.
Sub GetSheets()
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("D:\2018\ VBA\Consolidated Tracker.xlsm")
Workbooks("Source_Tracker.xlsx").Activate
For I = 1 To 3
Set Sheet = ActiveWorkbook.Sheets(I)
Columns("A:A").Select
Selection.Insert Shift:=xlToRight
Range("A1").Select
Dim LastRow As Long
LastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
With Range("A1:A" & LastRow)
.Value = Date
.NumberFormat = "mm/dd/yy"
End With
Range("A1").Select
ActiveCell.Offset(1, 0).Select
Selection.CurrentRegion.Copy
Workbooks("Consolidated Tracker").Activate
Set Sheet = Workbooks("Consolidated Tracker.xlsm").Sheets(I)
Range("A100000").Select
Selection.End(xlUp).Select
ActiveCell.Offset(1, 0).Select
ActiveCell.PasteSpecial
ActiveCell.Offset(0, 0).Select
Selection.EntireRow.Delete
Next I
End Sub
Consider this rewrite.
Option Explicit
Sub GetSheets()
Dim i As Long, lr As Long
Dim wb1 As Workbook, wb1 As Workbook
Application.Workbooks.Open Filename:="D:\2018\ VBA\Consolidated Tracker.xlsm", _
ReadOnly:=True, AddToMru:=False
setWbs wb1, wb2
With wb1
For i = 1 To 3
With .Worksheets(i)
.Columns("A:A").Insert Shift:=xlToRight
lr = Cells.Find(what:="*", after:=.Cells(1), _
SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
With .Range(.Cells(1, "A"), .Cells(lr, "A"))
.Value = Date
.NumberFormat = "mm/dd/yy"
End With
.Cells(1, "A").CurrentRegion.offset(1, 0).Copy _
Destination:=wb2.Worksheets(i).Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
End With
Next i
End With
End Sub
Sub setWbs(ByRef wkbk1 As Workbook, ByRef wkbk2 As Workbook)
Dim wb As Long
For wb = 1 To application.Workbooks.Count
Select Case left(LCase(Workbooks(wb).name), 7)
Case "source_"
Set wkbk1 = Workbooks(wb)
Case "consoli"
Set wkbk2 = Workbooks(wb)
End Select
Next wb
End Sub
I am trying to get data from every other sheet in the workbook and paste it into a master sheet (Sheet1), but when I run my code nothing happens, Can someone tell me why this is?
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
wb.Sheets("Sheet1").Cells(1, 1).Text = "Started"
i = 1
'cells is row,col
For Each objWorksheet In wb.Worksheets
'ws.Cells(1, i).Value = objWorksheet.Name
'objWorksheet.Activate
'ws = wb.ActiveSheet
doJStuff i, objWorksheet
i = i + 1
Next
wb.Sheets("Sheet1").Cells(1, 1).Text = "DONE"
End Sub
Sub doJStuff(row, ws)
ws.Select
Range("A2").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
ActiveSheet.Cells(row, 1).Select
ActiveSheet.Paste
'end paste name
'copy post history and transpose into row 2 on sheet1
ws.Select
Range("H2:H30").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
ActiveSheet.Cells(row, 2).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
'end post history
End Sub
You've got a number of problems with your code. First of all, avoid using Select wherever possible. Second, you are not properly assigning variables. You should put Option Explicit on the top of the module and then make sure you've assigned things correctly.
As for the actualy code, when you are copying/pasting the H2:H30 range into your first sheet you are going to only end up getting the first value in the range for every sheet except the last because you are pasting 28 rows but only incrementing the destination row by one. I didn't fix that but it's worth pointing out. I also left in your comments though they don't make much sense. Without knowing what you are trying to do, I've only cleaned up some of your code but it probably still won't work exactly right.
Sub YourSub()
Dim wb As Workbook
Dim wksht As Worksheet
Dim i As Integer
Set wb = ActiveWorkbook
wb.Sheets("Sheet1").Cells(1, 1).Text = "Started"
i = 1
'cells is row,col
For Each wksht In Worksheets
'ws.Cells(1, i).Value = objWorksheet.Name
'objWorksheet.Activate
'ws = wb.ActiveSheet
doJStuff i, wksht
i = i + 1
Next
wb.Sheets("Sheet1").Cells(1, 1).Text = "DONE"
End Sub
Sub doJStuff(row As Integer, ws As Worksheet)
ws.Range("A2").Copy
Sheets("Sheet1").Cells(row, 1).PasteSpecial
'end paste name
'copy post history and transpose into row 2 on sheet1
ws.Range("H2:H30").Copy
Sheets("Sheet1").Cells(row, 2).PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
'end post history
End Sub