The following is my VBA code, for some reason the code will run but not actually paste in the range I need it to paste. Anybody have any ideas why it won't paste my values?
The programs goes to my selected cell that I'm looking for, but now the activecell becomes my range and I'm trying to paste the it there. Any information will help, it just doesn't want to paste the values in the range I selected.
Sub Macro1()
Dim Form1033 As Worksheet
Dim CleaningSchedule As Worksheet
Set Form1033 = Worksheets("Form1033andForm1034")
Set CleaningSchedule = Worksheets("CleaningSchedule")
Dim Day As Range
Set Day = Form1033.Range("$J$3")
With Form1033
Range("$G$5:$G$18").Select
Selection.Copy
End With
With CleaningSchedule
Dim i As Integer
For i = 6 To 37
If Cells(4, i).Value = Day.Value Then
Cells(5, i).Select
Range(ActiveCell, Cells(ActiveCell.Rows + 13, ActiveCell.Column)).Select
Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End If
Next i
End With
Form1033.Select
Application.CutCopyMode = False
Range("$G$5:$G$18").ClearContents
MsgBox "Scoresheet Updated"
End Sub
I fixed the code here, but please read the link I provided in my comment, and you will not have these errors in the future.
I also commented the refactors I did to the code. Also, notice that I assigned the Cells and Ranges to the parent worksheet with .. (See #BruceWayne's link in his comment to your original question)
Sub Macro1()
Dim Form1033 As Worksheet
Dim CleaningSchedule As Worksheet
Set Form1033 = Worksheets("Form1033andForm1034")
Set CleaningSchedule = Worksheets("CleaningSchedule")
Dim Day As Range
Set Day = Form1033.Range("$J$3")
'copy the range directly
Form1033.Range("$G$5:$G$18").Copy
With CleaningSchedule
Dim i As Integer
For i = 6 To 37
If .Cells(4, i).Value = Day.Value Then
'paste directly to range and i also combined 13 rows plus row 5, since you are always using the same row
Range(.Cells(5,i), Cells(18,i)).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End If
Next i
End With
'clear contenst directly
Form1033.Range("$G$5:$G$18").ClearContents
MsgBox "Scoresheet Updated"
End Sub
Since you are using "With" statement, you need to add a "." in front of "cells" and "range" and any other references you make. For example:
With myWorksheet
.range("A1").copy
End with
So, the problem in this case is that you still remain on the same worksheet and clear the contents of the cells you had pasted.
Related
I'm fairly new to VBA user-forms so hopefully it's an easy fix.
I am using this code to move my entries from one sheet to another within the same workbook,but its working with some errors.
*I want it work on a specific sheet but its working on the active sheet.
**I want that after moving entries it should auto clear the specific sheet ( and I don't know how to do that :( )
Here is my code:
Private Sub CommandButton8_Click() 'Move Button
For Each cell In ThisWorkbook.Sheets("Daily").Range("endRange")
If IsDate(cell) = True Then
myEndRow = cell.Row
End If
Next cell
ThisWorkbook.Worksheets("Daily").Range("A2:E10000" & myEndRow).Select
Selection.Copy
Sheets("Data").Select
'Range("A2660").Select
ThisWorkbook.Worksheets("Data").Range("a99999").End(xlUp).Select
ActiveCell(2).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
End Sub
Here is the link for the file:
Link
In your daily sheet in the code associated with the button put the following.
Please note i am not sure of the purpose of your test to see if there is a date. If you can clarify this i can amend the code accordingly. You don't need a button in the data sheet as this is where you are copying to. Make sure this code only resides in the sheet associated with the button i.e. Daily and does not exist elsewhere in the workbook.
Private Sub CommandButton1_Click() 'Move Button
Dim wb As Workbook
Dim wsSource As Worksheet
Dim wsTarget As Worksheet
Dim rangeToCopy As Range
Set wb = ThisWorkbook
Set wsSource = wb.Worksheets("Daily")
Set wsTarget = wb.Worksheets("Data")
Dim NextRow As Long
NextRow = wsTarget.Cells(wsTarget.Rows.Count, "A").End(xlUp).Row + 1 'Find next free row in Data sheet
Set rangeToCopy = wsSource.Range("A1").CurrentRegion.Offset(1, 0) 'get current set of rows that have data excluding header in daily sheet
rangeToCopy.Copy wsTarget.Cells(NextRow, "A") 'copy the new data from daily across to the next free row in the data sheet
rangeToCopy.ClearContents 'clear the contents of the daily sheet under the header
End Sub
I have two sheets. One has the complete data and the other is based on the filter applied on the first sheet.
Name of the data sheet : Data
Name of the filtered Sheet : Hoky
I am just taking a small portion of data for simplicity. MY objective is to copy the data from Data Sheet, based on the filter. I have a macro which somehow works but its hard-coded and is a recorded macro.
My problems are:
The number of rows is different everytime. (manual effort)
Columns are not in order.
Sub TESTTHIS()
'
' TESTTHIS Macro
'
'FILTER
Range("F2").Select
Selection.AutoFilter
ActiveSheet.Range("$B$2:$F$12").AutoFilter Field:=5, Criteria1:="hockey"
'Data Selection and Copy
Range("C3").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Hockey").Select
Range("E3").Select
ActiveSheet.Paste
Sheets("Data").Select
Range("D3").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Hockey").Select
Range("D3").Select
ActiveSheet.Paste
Sheets("Data").Select
Range("E3").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Hockey").Select
Range("C3").Select
ActiveSheet.Paste
End Sub
Best way of doing it
Below code is to copy the visible data in DBExtract sheet, and paste it into duplicateRecords sheet, with only filtered values. Range selected by me is the maximum range that can be occupied by my data. You can change it as per your need.
Sub selectVisibleRange()
Dim DbExtract, DuplicateRecords As Worksheet
Set DbExtract = ThisWorkbook.Sheets("Export Worksheet")
Set DuplicateRecords = ThisWorkbook.Sheets("DuplicateRecords")
DbExtract.Range("A1:BF9999").SpecialCells(xlCellTypeVisible).Copy
DuplicateRecords.Cells(1, 1).PasteSpecial
End Sub
I suggest you do it a different way.
In the following code I set as a Range the column with the sports name F and loop through each cell of it, check if it is "hockey" and if yes I insert the values in the other sheet one by one, by using Offset.
I do not think it is very complicated and even if you are just learning VBA, you should probably be able to understand every step. Please let me know if you need some clarification
Sub TestThat()
'Declare the variables
Dim DataSh As Worksheet
Dim HokySh As Worksheet
Dim SportsRange As Range
Dim rCell As Range
Dim i As Long
'Set the variables
Set DataSh = ThisWorkbook.Sheets("Data")
Set HokySh = ThisWorkbook.Sheets("Hoky")
Set SportsRange = DataSh.Range(DataSh.Cells(3, 6), DataSh.Cells(Rows.Count, 6).End(xlUp))
'I went from the cell row3/column6 (or F3) and go down until the last non empty cell
i = 2
For Each rCell In SportsRange 'loop through each cell in the range
If rCell = "hockey" Then 'check if the cell is equal to "hockey"
i = i + 1 'Row number (+1 everytime I found another "hockey")
HokySh.Cells(i, 2) = i - 2 'S No.
HokySh.Cells(i, 3) = rCell.Offset(0, -1) 'School
HokySh.Cells(i, 4) = rCell.Offset(0, -2) 'Background
HokySh.Cells(i, 5) = rCell.Offset(0, -3) 'Age
End If
Next rCell
End Sub
When i need to copy data from filtered table i use range.SpecialCells(xlCellTypeVisible).copy. Where the range is range of all data (without a filter).
Example:
Sub copy()
'source worksheet
dim ws as Worksheet
set ws = Application.Worksheets("Data")' set you source worksheet here
dim data_end_row_number as Integer
data_end_row_number = ws.Range("B3").End(XlDown).Row.Number
'enable filter
ws.Range("B2:F2").AutoFilter Field:=2, Criteria1:="hockey", VisibleDropDown:=True
ws.Range("B3:F" & data_end_row_number).SpecialCells(xlCellTypeVisible).Copy
Application.Worksheets("Hoky").Range("B3").Paste
'You have to add headers to Hoky worksheet
end sub
it needs to be .Row.count not Row.Number?
That's what I used and it works fine
Sub TransfersToCleared()
Dim ws As Worksheet
Dim LastRow As Long
Set ws = Application.Worksheets("Export (2)") 'Data Source
LastRow = Range("A" & Rows.Count).End(xlUp).Row
ws.Range("A2:AB" & LastRow).SpecialCells(xlCellTypeVisible).Copy
I'm reasonably new to excel VBA and have hit a wall trying to develop a macro. I have output from an access database containing data in columns A to S. The output has a variable number of rows but always contains a header row. Column C has values which are common to several rows (i.e. C2:C7 might be 'Bananas', while C8:C9 might be 'Basket', and C10:C21 might be 'Bucket'), but the number of rows which have a common value in column C is dynamic. The values in column C are always contiguous.
I've been trying to create a macro which: identifies when the value in column C changes, pastes columns A to S for rows with the same value in column C (and the header row) to a new workbook saved with the column C value as the filename, deletes this range from the original workbook, and loops for the number of values in column C. My code seems to work if there are 3 values in column C; however, if there are more than this the code seems to ignore the criteria to look for a change in value in column C and creates new workbooks with ranges containing multiple values in column C.
I thought it may be due to the fact that the variables are not clearing for each iteration of the loop, but everything I've looked at on the web suggests this should not be an issue. The If statement seems to work when I've replaced the new workbook code with msgbox, but not with the workbook code. I believe it's a problem with the For loop but I'm not sure how to tackle that. I've googled and looked at countless SO pages but could not find an answer I could use. Any help would be much appreciated.
Here's my code:
Sub number()
Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet, wsO As Worksheet
Dim cell, rng As Range
Set rng = Range("C2:C97")
For Each cell In rng
If cell.Value <> cell.Offset(1, 0).Value Then
Set wbI = ActiveWorkbook
Set wsI = wbI.Worksheets("Worklist")
Set wbO = Workbooks.Add
With wbO
Set wsO = wbO.Sheets("Sheet1")
.SaveAs Filename:="C:\Users\svanwo0\Desktop\" & cell & ".xls", FileFormat:=56
wsI.Range("A1:S1").Copy
wsO.Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wsI.Rows("2:" & cell.Row).Copy
wsO.Range("A2").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
.Close SaveChanges:=True
End With
Set wbI = Nothing
Set wsI = Nothing
Set wbO = Nothing
Set wsO = Nothing
Rows("2:" & cell.Row).EntireRow.Delete (xlUp)
End If
Next cell
End Sub
Thanks in advance
vanw0001
This is one of those instances where going forward in a loop and deleting lines causes problems.
You have set the range it is going to iterate. As you delete the data is shifted up but you are still going to the next physical row, it does not reset each time
Since you are basically deleting the entire area of date i would wait till the end to delete. I would create a variable to hold the start row of the next block of data.
Sub number()
Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet, wsO As Worksheet
Dim cell, rng As Range
Dim stRw As Long
Set rng = Range("C2:C97")
stRw = 2
For Each cell In rng
If cell.Value <> cell.Offset(1, 0).Value Then
Set wbI = ActiveWorkbook
Set wsI = wbI.Worksheets("Worklist")
Set wbO = Workbooks.Add
With wbO
Set wsO = wbO.Sheets("Sheet1")
.SaveAs Filename:="C:\Users\svanwo0\Desktop\" & cell & ".xls", FileFormat:=56
wsI.Range("A1:S1").Copy
wsO.Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wsI.Rows(stRw & ":" & cell.Row).Copy
wsO.Range("A2").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
.Close SaveChanges:=True
stRw = cell.Row + 1
End With
Set wbI = Nothing
Set wsI = Nothing
Set wbO = Nothing
Set wsO = Nothing
End If
Next cell
Rows("2:97").EntireRow.Delete (xlUp)
End Sub
I have the following VBA code that takes a single row from Sheet "Tabled data", copies the data, then pastes the data into the next available row in Sheet "Running list". However the original row has formulas and I need the values to paste, not the formulas. I've seen numerous ways to do it with Range.PasteSpecial but this code didn't use Range and I'm not sure how to incorporate it.
Note: I modified this code from here: http://msdn.microsoft.com/en-us/library/office/ff837760(v=office.15).aspx. It originally had an IF statement to match content in a cell then paste it in a certain sheet according to the content in the cell. I only had one sheet to copy to and didn't need the IF. I don't really need to find the last row of data to copy either as it will only ever be one row with range of A2:N2. But if I take out the FinalRow section and the For and replace with Range("A2:N2") it doesn't work so I left those in.
Any guidance on how to add in the PasteValues property without making this more complicated? I'm also open to simplification of the For or FinalRow variable such as using Range. I'm only sort of familiar with VBA, having done a few things with it, but usually after much searching and modifying code.
Public Sub CopyData()
Sheets("Tabled data").Select
' Find the last row of data
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
' Loop through each row
For x = 2 To FinalRow
ThisValue = Cells(x, 1).Value
Cells(x, 1).Resize(1, 14).Copy
Sheets("Running list").Select
NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
Cells(NextRow, 1).Select
ActiveSheet.Paste
Sheets("Tabled data").Select
Next x
End Sub
Hopefully we can actually make this more simple.
Public Sub CopyRows()
Sheets("Sheet1").UsedRange.Copy
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
'check if the last cell found is empty
If IsEmpty(ActiveSheet.Cells(lastrow, 1)) = True Then
'if it is empty, then we should fill it
nextrow = lastrow
Else
'if it is not empty, then we should not overwrite it
nextrow = lastrow + 1
End If
ActiveSheet.Cells(nextrow, 1).Select
ActiveSheet.Paste
End Sub
edit: I expanded it a little so that there won't be a blank line at the top
I found a working solution. I recorded a macro to get the paste special in there and added the extra code to find the next empty row:
Sub Save_Results()
' Save_Results Macro
Sheets("Summary").Select 'renamed sheets for clarification, this was 'Tabled data'
'copy the row
Range("Table1[Dataset Name]").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
' paste values into the next empty row
Sheets("Assessment Results").Select
Range("A2").Select
NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
Cells(NextRow, 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
' Return to main sheet
Sheets("Data Assessment Tool").Select
End Sub
Just copy the data all at once, no need to do it a row at a time.
Sub CopyData()
With ThisWorkbook.Sheets("Tabled data")
Dim sourceRange As Range
Set sourceRange = .Range(.Cells(2, 1), .Cells(getLastRow(.Range("A1").Parent), 14))
End With
With ThisWorkbook.Sheets("Running list")
Dim pasteRow As Long
Dim pasteRange As Range
pasteRow = getLastRow(.Range("A1").Parent) + 1
Set pasteRange = .Range(.Cells(pasteRow, 1), .Cells(pasteRow + sourceRange.Rows.Count, 14))
End With
pasteRange.Value = sourceRange.Value
End Sub
Function getLastRow(ws As Worksheet, Optional colNum As Long = 1) As Long
getLastRow = ws.Cells(ws.Rows.Count, colNum).End(xlUp).Row
End Function
Private Sub Load_Click()
Call ImportInfo
End Sub
Sub ImportInfo()
Dim FileName As String
Dim WS1 As Worksheet
Dim WS2 As Worksheet
Dim ActiveListWB As Workbook
Dim check As Integer
'Application.ScreenUpdating = False
Set WS2 = ActiveWorkbook.Sheets("KE_RAW")
confirm = MsgBox("Select (.xlsx) Excel file for Data transfer." & vbNewLine & "Please ensure the sheets are named Sort List, Second and Third.", vbOKCancel)
If confirm = 1 Then
FileName = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*),*.xls*", _
Title:="Select Active List to Import", MultiSelect:=False)
If FileName = "False" Then
MsgBox "Import procedure was canceled"
Exit Sub
Else
Call CleanRaw
Set ActiveListWB = Workbooks.Open(FileName)
End If
Set WS1 = ActiveListWB.Sheets("Sort List")
WS1.UsedRange.Copy 'WS2.Range("A1")
' WS2.Range("A1").Select
WS2.UsedRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'WS2.Range ("A1")
ActiveWorkbook.Close False
'Call ClearFormulas
' Call RefreshAllPivotTables
Sheets("Key Entry Data").Select
'Sheets("Raw").Visible = False
'Application.ScreenUpdating = True
MsgBox "Data has been imported to workbook"
Else
MsgBox "Import procedure was canceled"
End If
Application.ScreenUpdating = True
End Sub
Sub CleanRaw()
Sheets("KE_RAW").Visible = True
Sheets("KE_RAW").Activate
ActiveSheet.Cells.Select
Selection.ClearContents
End Sub
I would like to ask for a help. My Macro was about to populate the current date to all populated rows. At the begining it seemed to work and suddenly it started to change (overwrite) the header to the current date and put the current date in 1 cell below. Could anyone help me what should I amend to make it work properly?
Here is the macro code (reformatted):
Sub DateVerified()
Sheets("Data").Activate
Dim rngAddress As Range
Set rngAddress = Range("A1:ZZ1").Find("Verified Date").Offset(1, 0)
rngAddress.Select
Dim ac As Integer
Dim lastr As Long
Dim sh As Worksheet
Set sh = ActiveSheet
ac = ActiveCell.Column
lastr = sh.Cells(Rows.Count, ac).End(xlUp).Row
Range(Cells(2, ac), Cells(lastr, ac)).Select
Selection.ClearContents
Selection.Formula = "=TEXT(Now(),""dd/mm/yyyy"")"
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
The following might suit:
Sub DateVerified()
Dim rngAddress As Range
Dim ac As Integer
Dim lastr As Long
Dim sh As Worksheet
Sheets("Data").Activate
Set rngAddress = Range("A1:ZZ1").Find("Verified Date").Offset(1, 0)
rngAddress.Select
Set sh = ActiveSheet
lastr = sh.Cells(Rows.Count, 1).End(xlUp).Row
ac = ActiveCell.Column
Range(Cells(2, ac), Cells(lastr, ac)).Select
Selection.ClearContents
Selection.Formula = "=TEXT(Now(),""dd/mm/yyyy"")"
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues
End Sub
I think that this is likely to be going wrong on the line below:
lastr = sh.Cells(Rows.Count, ac).End(xlUp).Row
This attempts to go to the final row of the spreadsheet for the active column and then do the equivalent of ctrl+up in excel to find the last row populated in that column. To test this theory add a line of code directly after this:
debug.print "lastr set to " & lastr
and see what this value is set to looking at the immediate window (use Ctrl+G to open from the VBA editor).