I have 2 worksheets, ws1 and ws2. This is the vba. It will go to ws2 and then ws1. I just want to see ws1 while ws2 does the copying job, and I do not want to juggle between ws1 and ws2.
How should I correct the vba?
Sheets("ws2").Select
Range("A3:AA3").Select
Selection.Copy
Range("A4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A4").Select
Application.CutCopyMode = False
Range("A4:AA4").Select
Selection.Insert Shift:=xlDown
Sheets("ws1").Select
The juggling is happening because you are telling excel to do the juggling :) And hence I always recommend not to use .SELECT/.ACTIVATE.
Directly perform the action. See this.
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("ws2")
With ws
.Range("A3:AA3").Copy
.Range("A4").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
.Range("A4:AA4").Insert Shift:=xlDown
End With
End Sub
Use
Application.ScreenUpdating = False
before you run the above code to stop viewing what your macro is doing.
so:
Sheets("ws1").Select
Application.ScreenUpdating = False
Range("A3:AA3").Select
.... etc
Application.ScreenUpdating = True
A forum entry on ozgrid provides a simple and elegant solution
Sub NameOfSub()
Application.ScreenUpdating = False
'Some Code Here
Application.ScreenUpdating = True
End Sub
Related
I have two cells (R5 and S5) that are aggregates based on a RAND() function. I want to create a running list of those values, which change every time the sheet recalculates. The list should have about 100K iterations of this. I wrote a "dumb" bit of VBA that copy/pastes the values into a list.
This does sort of work, but is too slow to scale to 100k iterations and I get a gap every 50 records for some reason.
There must be a better / faster way to do this with a loop or something like that? TIA.
Sub Macro2()
'
' Macro2 Macro
'
'
Range("R5:S5").Select
Selection.Copy
Range("U5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("U6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("U7").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
A Worksheet Calculate
Sheet Module e.g. Sheet1
Option Explicit
Private Sub Worksheet_Calculate()
Macro2 Me
End Sub
Standard Module e.g. Module1
Option Explicit
Sub Macro2(ByVal ws As Worksheet)
Application.EnableEvents = False
Dim lCell As Range
Set lCell = ws.Cells(ws.Rows.Count, "U").End(xlUp).Offset(1)
lCell.Resize(, 2).Value = ws.Range("R5:S5").Value
Application.EnableEvents = True
End Sub
I'm extremely new to VBAs and cannot figure out how to add a value to the next row if there's already data previous row. I'm sure I'm overthinking it, but I cannot seem to figure it out. Any help would be appreciated.
Below is the macro I'm using. Not sure if I need to offset the data or maybe add an if then statement of some sort.
Sub Archive_2()
Range("A2").Select
Selection.Copy
Sheets("Campaign Rate").Select
Range("A3").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
Use below sub-
Sub CopyPaste()
Dim sh As Worksheet
Dim lRng As Range
Set sh = Worksheets("Campaign Rate")
Set lRng = sh.Cells(sh.Rows.Count, 1).End(xlUp)
Range("A2").Copy
lRng.Offset(1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Set sh = Nothing
Set lRng = Nothing
End Sub
I am trying to copy the range of value from one sheet in excel to another. I have copied this formula from another part of my sheet that works however i cam coming up with the run time error 9.
Sub SaveJambStudEC()
'
' SaveCalcsJambEC Macro
'
Dim page As Integer
page = Cells(4, "T").Value
Range("A70:AN70").Select
Selection.Copy
Range("A71").Select
ActiveCell.Offset(page, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1:O63").Select
Selection.Copy
Sheets("10.3 JambCalcs EC").Select
Range("A1").Select
ActiveCell.Offset((page - 1) * 63, 0).Select
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone _
, SkipBlanks:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats
Sheets("9.3 Jamb Design EC").Select
Range("T5").Select
Selection.Copy
Range("N9").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("T31").Value = 0
Call JambECsetDesignOptions
Call CopyJambOptiValues
Range("J9").Activate
End Sub
using the below code you will check if there is a sheet with that name. if you dont receive any message box means that there is no sheet with such name
Option Explicit
Sub test()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name = "10.3 JambCalcs EC" Then
MsgBox "Sheet Appears"
Exit Sub
End If
Next ws
End Sub
Note
'ThisWorkbook' refer to the workbook that the code included. If you want to clearly declare the workbook you could declare a variable 'Dim wb as Workbook' and then set the workbook 'Set wb=Workbooks("workbook name")'
I've created a basic macro within a workbook to clear data from a set number of tabs then copy in refreshed data from external workbooks. There is a master data tab within the workbook that uses IF formulas to obtain various stock information for that tab which then feeds through to other sheets.
E.G.
=IF($A$2="","",SUMIF(Data_CoventryStock!$A:$A,Data!$A$2,Data_CoventryStock!$E:$E))
Currently when the macro runs it produces the desired result but the IF Formulas lose the reference to the range e.g. $A:$A becomes #N/A!
I've been looking online for a solution but am unable to see a suitable option. I am new to this area.
Sub Update()
'
' Update Macro
'
Application.DisplayAlerts = False
' Clears data from tabs
Sheets("Data_10Day").Select
Columns("A:B").Select
Selection.Delete Shift:=xlToLeft
Sheets("Data_CoventryStock").Select
Columns("A:E").Select
Selection.Delete Shift:=xlToLeft
Sheets("Data_CowleyStock").Select
Columns("A:E").Select
Selection.Delete Shift:=xlToLeft
Sheets("Data_RugbyStock").Select
Columns("A:B").Select
Selection.Delete Shift:=xlToLeft
Sheets("Data_10Day").Select
' Copies data from other workbooks then pastes
Workbooks.Open Filename:= _
"C:\Users\ceasdown\Documents\HDS\Data\Data_10Day.xlsx"
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Windows("Coventry Ordering Template2.xlsm").Activate
Sheets("Data_10Day").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Workbooks("Data_10Day.xlsx").Close
Workbooks.Open Filename:= _
"C:\Users\ceasdown\Documents\HDS\Data\Data_CoventryStock.xlsx"
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Windows("Coventry Ordering Template2.xlsm").Activate
Sheets("Data_CoventryStock").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Workbooks("Data_CoventryStock.xlsx").Close
Workbooks.Open Filename:= _
"C:\Users\ceasdown\Documents\HDS\Data\Data_CowleyStock.xlsx"
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Windows("Coventry Ordering Template2.xlsm").Activate
Sheets("Data_CowleyStock").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Workbooks("Data_CowleyStock.xlsx").Close
Workbooks.Open Filename:= _
"C:\Users\ceasdown\Documents\HDS\Data\Data_RugbyStock.xlsx"
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Windows("Coventry Ordering Template2.xlsm").Activate
Sheets("Data_RugbyStock").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Workbooks("Data_RugbyStock.xlsx").Close
Application.DisplayAlerts = True
End Sub
I need it to retain the cell range in the IF formula so no manual update after running the macro is required.
The reason your formulas get damaged is that you are Deleting the ranges they refer to. Instead of deleting, use ClearContents instead.
Also, your code can do with quite a bit of optimsation.
Consider this
Sub Update()
Dim wbMain As Workbook
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim FilePath As String
Application.DisplayAlerts = False
Set wbMain = ActiveWorkbook
With wbMain
FilePath = Environ$("UserProfile") & "\Documents\HDS\Data\"
' Copies data from other workbooks then pastes
UpdateFromWB .Worksheets("Data_10Day").Cells(1, 1), FilePath & "Data_10Day.xlsx", "WhatSheet?"
UpdateFromWB .Worksheets("Data_CoventryStock").Cells(1, 1), FilePath & "Data_CoventryStock.xlsx", "WhatSheet?"
UpdateFromWB .Worksheets("Data_CowleyStock").Cells(1, 1), FilePath & "Data_CowleyStock.xlsx", "WhatSheet?"
UpdateFromWB .Worksheets("Data_RugbyStock").Cells(1, 1), FilePath & "Data_RugbyStock.xlsx", "WhatSheet?"
End With
Application.DisplayAlerts = True
End Sub
Private Sub UpdateFromWB(rngDest As Range, wbName As String, wsName As String)
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Set wb = Workbooks.Open(Filename:=wbName)
Set ws = wb.Worksheets(wsName)
With ws
Set rng = .Range(.Cells(1, 1).End(xlDown), .Cells(1, 1).End(xlToRight))
'Alternative, in case there might be gaps in the data
'Set rng = .Range(.Cells(.Rows.Count, 1).End(xlUp), .Cells(1, .Columns.Count).End(xlToLeft))
End With
rngDest.Worksheet.Cells.ClearContents 'Delets ALL data from sheet. Adjust range if required
rngDest.Resize(rng.Rows.Count, rng.Columns.Count).Value = rng.Value
wb.Close
End Sub
I try to create a code avoiding .Select, .Activate and repetition. The code is untested but it will give you an idea about the concept. For any question please ask me.
Option Explicit
Sub Update()
Dim ws As Worksheet
'
' Update Macro
'
Application.DisplayAlerts = False
' Clears data from tabs
For Each ws In ThisWorkbook
With ws
If .Name = "Data_10Day" Or .Name = "Data_RugbyStock" Then
.Columns("A:B").Delete Shift:=xlToLeft
ElseIf .Name = "Data_CoventryStock" Or .Name = "Data_CowleyStock" Then
.Columns("A:E").Delete Shift:=xlToLeft
End If
End With
Next ws
' Copies data from other workbooks then pastes
Call Procedure("Data_10Day.xlsx", "Data_10Day")
Call Procedure("Data_CoventryStock.xlsx", "Data_CoventryStock")
Call Procedure("Data_CowleyStock.xlsx", "Data_CowleyStock")
Call Procedure("Data_RugbyStock.xlsx", "Data_RugbyStock.xlsx")
Application.DisplayAlerts = True
End Sub
Sub Procedure(ByVal FileName As String, ByVal SheetName As String)
Workbooks.Open FileName:="C:\Users\ceasdown\Documents\HDS\Data\" & FileName
Workbooks(FileName).Sheets("Sheet1").UsedRange.Copy
Workbooks("Coventry Ordering Template2.xlsm").Sheets(SheetName).Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Workbooks(FileName).Close
End Sub
I'm trying to write a macro that will Open files one by one in a provided directory, calculate all formulas, paste values over specific formulas, save, and exit, repeat process with next file. Here's what i have below:
Sub LoopPaloSnapshot()
Dim wb As Workbook
Dim ws As Worksheet
Dim MyPath As String
Dim FldrPicker As FileDialog
Dim FSO As New FileSystemObject
Dim MyFolder As Folder
Dim SubFolder As Folder
Dim MyFile2 As File
Application.ScreenUpdating = True
Application.EnableEvents = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
MyPath = .SelectedItems(1) & "\"
End With
Set FSO = CreateObject("scripting.filesystemobject")
'In Case of Cancel
NextCode:
MyPath = MyPath
Set MyFolder = FSO.GetFolder(MyPath)
For Each SubFolder In MyFolder.SubFolders
For Each MyFile2 In SubFolder.Files
If FSO.GetExtensionName(MyFile2.Path) = "xlsx" Then
Set wb = Workbooks.Open(Filename:=MyFile2, UpdateLinks:=0)
Set ws = wb.Worksheets("Staffing Model")
Application.Run ("PALO.CALCSHEET")
Application.Calculate
Application.Run ("PALO.CALCSHEET")
Application.Calculate
Application.Calculation = xlCalculationManual
ws.Range("B1").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks _
:=False, Transpose:=False
ws.Range("F10:Q10").Value = ws.Range("F10:Q10").Value
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks _
:=False, Transpose:=False
ws.Range("F20:Q22").Value = ws.Range("F20:Q22").Value
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks _
:=False, Transpose:=False
ws.Range("F42:Q43").Value = ws.Range("F42:Q43").Value
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks _
:=False, Transpose:=False
ws.Range("F56:Q56").Value = ws.Range("F56:Q56").Value
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks _
:=False, Transpose:=False
ws.Range("F61:Q61").Value = ws.Range("F61:Q61").Value
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks _
:=False, Transpose:=False
ws.Range("F66:Q66").Value = ws.Range("F66:Q66").Value
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks _
:=False, Transpose:=False
'Break Links
If Not IsEmpty(wb.LinkSources(xlExcelLinks)) Then
For Each link In wb.LinkSources(xlExcelLinks)
wb.BreakLink link, xlLinkTypeExcelLinks
Next link
End If
Dim xWs As Worksheet
For Each xWs In Application.ActiveWorkbook.Worksheets
If xWs.Name <> "Staffing Model" Then
xWs.Delete
End If
Next
'Save and Close Workbook
wb.Close SaveChanges:=True
'Loop
End If
Next
Next
MsgBox "Task Complete!"
ResetSettings:
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
End Sub
After running this, i open the newly saved files and there are #Value errors in place of the formulas im attempting to calculate and paste values over. I've tried walking through the macro line by line and it seems to be working properly for the most part, but for some reason the formulas are not calculating. if i open the file manually prior to running the macro, everything calculates perfectly so im wondering if something is causing these formulas to not calculate while the macro is running. any help would be appreciated.
EDIT: the formulas im copying and pasting values over are HLOOKUP's pulling from other tabs within the workbook, and PALO formulas pulling data directly from a JEDOX server. i've manually ran through the process im trying to automate without errors.
Instead of copying and pasting complex formulas, I'd suggest writing the formulas directly into the cells using this method:
Worksheets("Sheet1").Range("A1").Formula = "=$A$4+$A$10"
Pasted formulas can sometimes carry references to the original worksheet which causes chaos, whereas an explicitly set formula will not do that.
If you're really trying to take it offline then you could also use this method to set values as well.
Worksheets("Sheet1").Range("A1").Value = "100"