I need to create a loop for this macro:
Sub Site_No()
' Site_No Macro
' Keyboard Shortcut: Ctrl+Shift+J
Range("D2").Select
Selection.Copy
Sheets("Spray Sheet").Select
Range("F5:J6").Select
ActiveSheet.Paste
ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
IgnorePrintAreas:=False
End Sub
Ideally I'd like to loop it through from D2 - D79.
If someone could show me where to place the loop i'd be very grateful
Ollie
I will not provide you the code, but will give you some hints to achieve your goal.
Sub Site_No()
'
' Start your loop here from D1 to D79. I suggest to use Cells(Row, Column) notation.
Range("D2").Select 'There is no need to select the cell
Selection.Copy 'Instead of Copy, you can use .Value
Sheets("Spray Sheet").Select 'There is no need to select the Sheet
Range("F5:J6").Select 'There is no need to select the cell
ActiveSheet.Paste 'You don't need to paste the value.
'End loop here if you need to print only once.
ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
IgnorePrintAreas:=False
End Sub
You can see this question for an example to "copy/paste" cell content using .Value.
Copy/Paste Loop through worksheets to consolidate
Something like this should be enough:
Public Sub TestMe()
Dim lngRow As Long
For lngRow = 2 To 79
ActiveSheet.Cells(lngRow, "D") = Worksheets("Spray Sheet").Cells(lngRow, "F")
Next lngRow
End Sub
Using select and activate is something that you should try to avoid as much as possible - How to avoid using Select in Excel VBA (said by the guy who used ActiveSheet in his code).
Related
I am trying to create a sheet that I can fill in, when i click the button it copies the information from the box and paste (and Transpose) to the Rawdata tab, then deletes the information from the Dashboard and saves the file.
I have recorded a simple macro to do this for me, but the problem is that I dont know how to get it to add the data to the next free row, it just replaces the information already there, this is the code i am using to try make it happen
Sub Macro5()
'
' Macro5 Macro
'
'
Range("C3:C8").Select
Selection.Copy
Sheets("RawData").Select
Cells(Range("C1000000").End(xlUp).Row + 1, 3).PasteSpecial Paste:=xlValues,
Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Sheets("Dasboard").Select
Application.CutCopyMode = False
ActiveWorkbook.Save
Range("C3:C8").Select
Selection.ClearContents
End Sub
any help here would be much appreciated.
I need it to transpose paste in the A:F columns
thank you
I recommend to read How to avoid using Select in Excel VBA. Using .Select is a very bad practice and results in many errors soon or later:
A better technique is defining worksheets and ranges so you can access them directly with a variable:
Option Explicit
Public Sub CopyData()
'define source range
Dim SourceRange As Range
Set SourceRange = ThisWorkbook.Worksheets("Dashboard").Range("C3:C8")
'find next free cell in destination sheet
Dim NextFreeCell As Range
Set NextFreeCell = ThisWorkbook.Worksheets("RawData").Cells(Rows.Count, "A").End(xlUp).Offset(RowOffset:=1)
'copy & paste
SourceRange.Copy
NextFreeCell.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
ThisWorkbook.Save
SourceRange.ClearContents
End Sub
Try a direct value transfer without Select.
Sub Macro5()
dim ws as worksheet
set ws = workSheets("RawData")
with worksheets("Dasboard").Range("C3:C8")
ws.cells(rows.count, "A").end(xlup).offset(1, 0).resize(.columns.count, .rows.count) = _
application.transpose(.value)
.clearcontents
.parent.parent.save
end with
End Sub
I'm trying to copy data into new workbook and validate the data by removing duplicates keeping one cell value as the source.
All I wanted is the count of XD in the worksheet provided there are no duplicate Record locator.
Also I wanted the count to be in a msgbox. Can someone help ?
Sub openworkbook()
Workbooks.Open ("C:\Users\kjayachandiran\Desktop\ACUITY CF 1204-1210.xls")
Worksheets(2).Activate
Cells.Select
Selection.Copy
Workbooks.Open ("C:\Users\kjayachandiran\Desktop\New-Manjunath.xlsx")
Worksheets(1).Activate
Range("A1").Select
ActiveSheet.Paste
Workbooks(3).Save
Workbooks(2).Close
ActiveWorkbook.Activate
Worksheets(1).Activate
Cells(1, 1).Select
Range("A366655").Value = Application.WorksheetFunction.CountIf(Columns(9), "=" & "XD")
End Sub
I have two sheets:
SheetA has a list of employee Nr.
Sheet B has a form that needs to be filled out AND printed with each employee numbers on it (then vlookup formulas fill out the rest)
Now I can copy paste each employee ID manually, but there are 330+ employees, that is a bit too much.
I would like to copy cell A2 in Sheet_A, paste it into cell A2 Sheet_B AND print the form, then go to cell A3 in Sheet_A copy it, paste it into A2 in Sheet_B and so on... I would like to repeat this process 337 times.
I created this macro, but I don't know how to make it always choose the next cell in Sheet_A AND repeat itself 337 times. (or depending on how many employees we have at a certain time)
Sub Copy_Cell()
' Copy_Cell Macro
Sheets("Sheet A").Select
Range("A2").Select
Selection.Copy
Sheets("Sheet B").Select
Range("A2").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
IgnorePrintAreas:=False
End Sub
You just need to loop through each of your rows:
Sub Copy_Cell()
Dim r As Long
'Use a "With" block to save having to constantly type "Worksheets("Sheet A")"
'inside the block
With Worksheets("Sheet A")
'Loop through all values in column A, thus saving the trouble of
'hard-coding the last row number to be used
For r = 2 To .Cells(.Rows.Count, "A").End(xlUp).Row
'Just copy the value directly from one worksheet to another, thus
'avoiding copy/paste
Worksheets("Sheet B").Range("A2").Value = .Cells(r, "A").Value
Worksheets("Sheet B").PrintOut Copies:=1, _
Collate:=True, _
IgnorePrintAreas:=False
Next r
End With
End Sub
Sub Copy_Cell() ' Copy_Cell Macro
Dim i as Integer
For i = 1 To 337
Sheets("Sheet A").Activate
ActiveSheet.Cells(i + 1, 1).Select
Selection.Copy
Sheets("Sheet B").Activate
Range("A2").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
IgnorePrintAreas:=False
Next i
End Sub Image Image
Sub Copy_Cell()
Dim row as Integer
Do While row <= 337
Sheets("Sheet A").Activate
Sheets("Sheet A").Cells(row + 1, 1).Copy
Sheets("Sheet B").Activate
Range("A2").Select
ActiveSheet.Paste
ActiveWindow.SelectedSheets.PrintOut Copies:=1
row = row + 1
Loop
End sub
I'm interning and was given an assignment in VBA, which I know very little about. I found code that is similar to the functions I need and have commented it with my best guesses. If you could help me understand what each piece does and where to replace the generic code with my own information, it would be greatly appreciated!
When patrons have an overdue record, they are sent a spreadsheet with a list of the records they must return and the records' attributes in the following columns.
I need to create a macro which will
Create a new workbook
Copy row 1 (headings)
Copy rows with the same User
Name the file “UniqueUserrecordsrecall.xlsx”
Save to C:\Users\xxx\Documents\xxx\xxx
Attributes: Records, Description, Client, Engagement, Days, Date, Type, LOS, Location, State, Final, User.
Workbook Name: RecordsRecall
Worksheet Name: Main
Sub details()
'Declaration
Dim thisWB As String
Dim newWB As String
thisWB = ActiveWorkbook.Name
'?
On Error Resume Next
Sheets("tempsheet").Delete
On Error GoTo 0
'CreateTempSheet
Sheets.Add
ActiveSheet.Name = "tempsheet"
'?
Sheets("Main").Select
If ActiveSheet.AutoFilterMode Then
Cells.Select
On Error Resume Next
ActiveSheet.ShowAllData
On Error GoTo 0
End If
'Copy User Column
Columns("L:L").Select
Selection.Copy
'Paste User Column in TempSheet
Sheets("tempsheet").Select
Range("A1").Select
ActiveSheet.Paste
Application.CutCopyMode = False
'?
If (Cells(1, 1) = "") Then
LastRow = Cells(1, 1).End(xlDown).Row
If LastRow <> Rows.Count Then
Range("A1:A" & LastRow - 1).Select
Selection.Delete Shift:=xlUp
End If
End If
'Apply Unique Filters in Tempsheet
Columns("A:A").Select
Columns("A:A").AdvancedFilter Action:=xlFilterCopy, _
CopyToRange:=Range("B1"), Unique:=True
'?
Columns("A:A").Delete
Cells.Select
Selection.Sort _
Key1:=Range("A2"), Order1:=xlAscending, _
Header:=xlYes, OrderCustom:=1, _
MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
lMaxSupp = Cells(Rows.Count, 1).End(xlUp).Row
For suppno = 2 To lMaxSupp
Windows(thisWB).Activate
supName = Sheets("tempsheet").Range("A" & suppno)
If supName <> "" Then
Workbooks.Add
ActiveWorkbook.SaveAs supName
newWB = ActiveWorkbook.Name
Windows(thisWB).Activate
Sheets("Main").Select
Cells.Select
If ActiveSheet.AutoFilterMode = False Then
Selection.AutoFilter
End If
Selection.AutoFilter Field:=2, Criteria1:="=" & supName, _
Operator:=xlAnd, Criteria2:="<>"
LastRow = Cells(Rows.Count, 2).End(xlUp).Row
'Copy from TempSheet
Rows("1:" & LastRow).Copy
'Paste in newWB in TempSheet
Windows(newWB).Activate
ActiveSheet.Paste
'Save and Close newWB
ActiveWorkbook.Save
ActiveWorkbook.Close
End If
Next
'Delete TempSheet
Sheets("tempsheet").Delete
Sheets("Main").Select
If ActiveSheet.AutoFilterMode Then
Cells.Select
ActiveSheet.ShowAllData
End If
End Sub
Thanks for the help!
I am guessing this code does not achieve the effect you seek and you do not know where to start fixing it.
You are attempting too much in one go when you do not really know what you are doing.
I suggest you start by writing simple macros each of which achieves one step of your total requirement or adds one step to a previous macro. If you run into difficulties with one of these macros, you can post it with an explanation of what it does and what you want it to do. Questions with macros that isolate a single problem get answered very quickly. I would not know where to start debugging your current macro.
You have an AutoFilter but I cannot see how that selects the records of a patron with an overdue record. I think that is your first problem: how does the macro know which patron’s records are to be output? Could this be supName? Where has this come from?
Can you write a macro that creates an empty workbook and saves it with the desired name? Call that Macro1.
Write Macro2 by updating Macro1, to rename Sheet1 as “Overdue” or something more meaningful and then delete the other worksheets.
Can you write a macro that uses AutoFilter to select the required records? Write this as new macro Macro3.
Merge Macro2 and Macro3 and try copying the rows selected by AutoFilter to the new workbook. The statement SourceRange.Copy Destination:=FirstDestCell is likely to be easier to use than Copy and Paste.
I hope you can see why little macros which expand your knowledge one step at a time will be an easier path to your objective than trying to debug your current code.
I used Macro Recorder in Excel to record a series of tasks I need to automate. These tasks happen between two different Excel spreadsheets. I believe that the macro performs the code on the current worksheet, but right now the second sheet is hard coded. How do I prompt the user to choose an Excel sheet to reference to?
The workbook that is going to have the macro is the MasterHardwareDB & the file that needs to be replaced with a user input is Computer&DeploymentInfo_06_23_15_v3.xlsx
I was researching the filedialog object but I am not sure how to integrate here.
Sub AutomateCompare()
'
' AutomateCompare Macro
'
ActiveCell.Select
ActiveCell.FormulaR1C1 = _
"=INDEX('Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[scheduleddate],MATCH([ #HostName],'Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[computername],0))"
ActiveCell.Offset(1, 0).Range("MasterHardwareDB[[#Headers],[Name]]").Select
ActiveCell.FormulaR1C1 = _
"=INDEX('Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[scheduleddate],MATCH([#HostName],'Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[computername],0))"
ActiveCell.Offset(1, 0).Range("MasterHardwareDB[[#Headers],[Name]]").Select
ActiveWindow.SmallScroll ToRight:=-1
ActiveCell.Offset(-2, 1).Range("MasterHardwareDB[[#Headers],[Name]]").Select
ActiveCell.FormulaR1C1 = _
"=INDEX('Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[forecastdate],MATCH([#HostName],'Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[computername],0))"
ActiveWindow.SmallScroll ToRight:=1
ActiveCell.Offset(1, 0).Range("MasterHardwareDB[[#Headers],[Name]]").Select
ActiveWindow.SmallScroll ToRight:=-7
ActiveSheet.ListObjects("MasterHardwareDB").Range.AutoFilter Field:=9, _
Criteria1:="FALSE"
ActiveWindow.SmallScroll ToRight:=1
ActiveCell.Offset(4169, -4).Range("MasterHardwareDB[[#Headers],[Name]:[EmpID]]") _
.Select
ActiveCell.Offset(521, 1).Range("MasterHardwareDB[[#Headers],[Name]]").Select
ActiveWindow.SmallScroll ToRight:=-7
ActiveSheet.ListObjects("MasterHardwareDB").Range.AutoFilter Field:=5, _
Criteria1:="=Scheduled", Operator:=xlOr, Criteria2:="=To Be Scheduled"
ActiveCell.Offset(87, -8).Range("MasterHardwareDB[[#Headers],[Name]]").Select
ActiveWindow.SmallScroll ToRight:=8
End Sub
The easiest way to do this is
shtNum = InputBox("Enter the number of the sheet you want to use.")
With Sheets(shtNum)
Your code here
End With
Also, just so you know, macro recorder code contains a lot of junk. Here is a cleaned-up version of your code.
Sub AutomateCompare()
With ActiveSheet
'Change the ranges to what you need. Using activecell is usually dangerous
.Range("A1:A2").FormulaR1C1 = "=INDEX('Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[scheduleddate],MATCH([ #HostName],'Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[computername],0))"
.Range("B1").FormulaR1C1 = "=INDEX('Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[forecastdate],MATCH([#HostName],'Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[computername],0))"
.ListObjects("MasterHardwareDB").Range.AutoFilter Field:=9, Criteria1:="FALSE"
.ListObjects("MasterHardwareDB").Range.AutoFilter Field:=5, Criteria1:="=Scheduled", Operator:=xlOr, Criteria2:="=To Be Scheduled"
End With
End Sub
Edit: Here is code that opens another workbook
Sub AutomateCompare()
Dim fileBrowse As FileDialog
Dim shtNum As Integer
Set fileBrowse = Application.FileDialog(msoFileDialogOpen)
If fileBrowse.Show = True Then wbPath = fileBrowse.SelectedItems(1)
With Workbooks.Open(wbPath)
shtNum = InputBox("Enter the number of the sheet you want to use.")
With .Sheets(shtNum)
'Change the ranges to what you need. Using activecell is usually dangerous
.Range("A1:A2").FormulaR1C1 = "=INDEX('Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[scheduleddate],MATCH([ #HostName],'Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[computername],0))"
.Range("B1").FormulaR1C1 = "=INDEX('Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[forecastdate],MATCH([#HostName],'Computer&DeploymentInfo_06_23_15_v3.xlsx'!Table1[computername],0))"
.ListObjects("MasterHardwareDB").Range.AutoFilter Field:=9, Criteria1:="FALSE"
.ListObjects("MasterHardwareDB").Range.AutoFilter Field:=5, Criteria1:="=Scheduled", Operator:=xlOr, Criteria2:="=To Be Scheduled"
End With
End With
End Sub