loop not iterating through list vba - vba

The list seems to be only selecting the first cell in the list, can someone tell me where I am going wrong?
Everytime I run this, it takes the first cell in the list assigns that value to the cell in ATL tab (which will then run numerous formulas) and copies the range that I want and pastes on the Final tab. I want it to do this, but it will not move down the list to the other cells. I have about 40 cells that it should be iterating through, but it simply won't work. Any ideas?
Dim x As Integer
Dim List As Range
Dim intcount As Integer
Dim DCs As Worksheet
Dim Form As Worksheet
Dim Final As Worksheet
Dim DCdata As String
Dim wsList As String
Dim rnglistrange As Range
With ThisWorkbook
Set DCs = .Sheets("List1")
Set Form = .Sheets("ATL")
Set Final = .Sheets("Final")
End With
DCs.Select
intcount = DCs.Cells(Rows.Count, "A").End(xlUp).Row '--Get last row of list.
Set List = DCs.Range("A1:A" & intcount) '--Qualify our list.
For Each rnglistrange In List '--For every name in list...
Form.Select
Range("A2") = List.Value
Range("A632:N646").Copy
Final.Select
ActiveCell.SpecialCells(xlLastCell).Select
Selection.End(xlToLeft).Select
Selection.Offset(2, 0).Select
ActiveCell.Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Next

the problem is in:
Range("A2") = List.Value
that would just put first value of List range in cell "A2"
while you want to put:
Range("A2") = rnglistrange
which would put current List cell Value in cell A2
but you may also want to consider this refactoring of your code, which has the main goal to avoid Select/Selection/Activate/ActiveXXX pattern in favor of fully qualified range references to both not loose control over what you're actually referencing and improve performance (and screen flickering)
Option Explicit
Sub main()
Dim listRng As Range, listCell As Range
Dim DCs As Worksheet, Form As Worksheet, Final As Worksheet
With ThisWorkbook
Set DCs = .Worksheets("List1")
Set Form = .Worksheets("ATL")
Set Final = .Worksheets("Final")
End With
With DCs
Set listRng = .Range("A1", .Cells(Rows.count, "A").End(xlUp)) '--Qualify our list.
End With
For Each listCell In listRng '--For every name in list...
With Form
.Range("A2") = listCell
.Range("A632:N646").Copy
End With
With Final
With .Cells(Rows.count, "A").End(xlUp).Offset(2)
.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End With
End With
Next
End Sub

Line 25 of your listing says:
Range("A2") = List.Value
Change that line to:
Range("A2") = rnglistrange.Value
You will see then that it is iterating through the cells of your "List" range.

Related

Copy data from one workbook to another while performing a check

Completely new to VBA. But here is the code I have. The first code box is to perform a check that Cell X in Workbook1 equals Cell Y in Workbook2, if successful it will continue to my second code box where it will pull the data from the designated cells and then paste it in the row where the active cell is currently located. The second code box needs an overhaul to designate the paste function into the active row, starting at the active cell.
I get errors trying to get the row where the active cell is currently located.
Here's the flow..
Command Button Click
Select File with data to be copied from (this workbook has static cells so data is being pulled from the same cell regardless of which spreadsheet is being used)
Perform a check that workbook1 process number (static cell) matches process number in workbook 2 in the current row where active cell is located (same column, changing rows)
4a. Success- Proceed to copy and paste data into active row beginning at the active cell
4b. Fail- Error message and don't copy or paste.
Code:
Sub Foo()
Dim vFile As Variant
Dim wbCopyTo As Workbook
Dim wsCopyTo As Worksheet
Dim wbCopyFrom As Workbook
Dim wsCopyFrom As Worksheet
Set wbCopyTo = ActiveWorkbook
Set wsCopyTo = ActiveSheet
'-------------------------------------------------------------
'Open file with data to be copied
vFile = Application.GetOpenFilename("Excel Files (*.xl*)," & _
"*.xl*", 1, "Select Excel File", "Open", False)
'If Cancel then Exit
If TypeName(vFile) = "Boolean" Then
Exit Sub
Else
Set wbCopyFrom = Workbooks.Open(vFile)
Set wsCopyFrom = wbCopyFrom.Worksheets(1)
End If
'Process number check to see if values match and the data is being put in the correct row
Dim projectNumber As Long
Dim column As Integer
Dim row As Integer
Dim rng As Range
'Set column and row to whatever row/column contains the Project Number in wsCopyFrom (could also use Range if its a particular cell)
projectNumber = wsCopyFrom.Range("G5).Value
Set rng = wsCopyTo.Cells.EntireRow.Select 'Get selected row in Active Worksheet
For Each c In rng.Cells ' Check each cell in row/range
If c.Value = projectNumber ' Project number was found
MsgBox("Project number found!")
' Insert copy and pasting code here.... See below code box
End If
Next c
' Project number was not found in selected range if you get to this point
MsgBox("Project Number Does Not Match")
'Close file that was opened
wbCopyFrom.Close SaveChanges:=False
Code:
'Copy and Pasting
wsCopyFrom.Range("F21").Copy
wsCopyTo.Range("Active Row, beginning at Active Cell").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wsCopyFrom.Range("G21").Copy
wsCopyTo.Range("Active Row and Offset one column to the right from previous cell").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wsCopyFrom.Range("L21").Copy
wsCopyTo.Range("Active Row and Offset one column to the right from previous cell").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wsCopyFrom.Range("M21").Copy
wsCopyTo.Range("Active Row and Offset one column to the right from previous cell").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wsCopyFrom.Range("R21").Copy
wsCopyTo.Range("Active Row and Offset one column to the right from previous cell").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wsCopyFrom.Range("S21").Copy
wsCopyTo.Range("Active Row and Offset one column to the right from previous cell").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wsCopyFrom.Range("G31").Copy
wsCopyTo.Range("Active Row and Offset one column to the right from previous cell").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wsCopyFrom.Range("M31").Copy
wsCopyTo.Range(""Active Row and Offset one column to the right from previous cell).PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wsCopyFrom.Range("S31").Copy
wsCopyTo.Range("Active Row and Offset one column to the right from previous cell").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wsCopyFrom.Range("F41").Copy
wsCopyTo.Range(""Active Row and Offset one column to the right from previous cell).PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
wsCopyFrom.Range("G41").Copy
wsCopyTo.Range("Active Row and Offset one column to the right from previous cell").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
If what you want is to copy from 1 file and paste it on another file without pasting it over already existing content then you should opt for a VBscript instead of excel.
Example below:
strPathSrc = "C:\......" ' Source files folder
strMaskSrc = "*.csv" ' Source files filter mask can be any format
iSheetSrc = 3 ' Source sheet index or name sheet you want to copy
strPathDst = "C:\....xlsx" ' Destination file
iSheetDst = 1 ' Destination sheet index or name
Set objExcel = CreateObject("Excel.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
objExcel.Visible = false
Set objWorkBookDst = objExcel.Workbooks.Open(strPathDst)
Set objSheetDst = objWorkBookDst.Sheets(iSheetDst)
Set objShellApp = CreateObject("Shell.Application")
Set objFolder = objShellApp.NameSpace(strPathSrc)
Set objItems = objFolder.Items()
objItems.Filter 64 + 128, strMaskSrc
objExcel.DisplayAlerts = False
For Each objItem In objItems
Set objWorkBookSrc = objExcel.Workbooks.Open(objItem.Path)
Set objSheetSrc = objWorkBookSrc.Sheets(iSheetSrc)
GetUsedRange(objSheetSrc).Copy
Set objUsedRangeDst = GetUsedRange(objSheetDst)
iRowsCount = objUsedRangeDst.Rows.Count
objWorkBookDst.Activate
objSheetDst.Cells(iRowsCount + 1, 1).Select
objSheetDst.Paste
objWorkBookDst.Application.CutCopyMode = False
objWorkBookSrc.Close
Next
objExcel.ActiveWorkbook.Save
fso.DeleteFile "C:......", True 'delete original file if required
Function GetUsedRange(objSheet)
With objSheet
Set GetUsedRange = .Range(.Cells(1, 1), .Cells(.UsedRange.Row + .UsedRange.Rows.Count - 1, .UsedRange.Column + .UsedRange.Columns.Count - 1))
End With
End Function
Paste this into a notepad and save it as .vbs then run it and should have you sorted. you can even automate this with windows scheduler if necessary.
Hope it helps

Copy data from one sheet and move to other problems

I'm trying to copy some rows from a sheet and then paste in other sheet that will contain the data. Later on I will erase the data form the original sheet to be fulfill again and repeat process.
My problem is that, it looks like I'm coping as well the empty cells from the original sheet so when paste for any reason excel consider this empty cell as the last one. More than sure I'm doing something wrong, the macro is this:
Sub CopyTable()
'
' CopyTable Macro
'
'
' Variables
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Set sht = Worksheets("Form")
Set StartCell = Range("A9")
'Refresh UsedRange
Worksheets("Form").UsedRange
'Find Last Row and Column
LastRow = StartCell.SpecialCells(xlCellTypeLastCell).Row
LastColumn = StartCell.SpecialCells(xlCellTypeLastCell).Column
'Select Range
sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select
' Copy range and move to Data sheet
Selection.Copy
Sheets("Data").Select
' Place pointer on cell A1 and search for next empty cell
Range("A1").Select
Do While Not IsEmpty(ActiveCell)
ActiveCell.Offset(1, 0).Select
Loop
' Once find, go back once to place on last empty and paste data from Form sheet no formating
ActiveCell.Offset(0, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
End Sub
I assume that the data from the form always has an entry in column A - that there are no entries where A is blank but other cells on the row are not blank:
Sub CopyTable()
Dim sourcesheet As Worksheet
Dim DestSheet As Worksheet
Dim Source As Range
Dim dest As Range
Dim Startcell As Range
Set sourcesheet = ThisWorkbook.Worksheets("Form")
Set Startcell = sourcesheet.Range("A9")
Set Source = sourcesheet.Range(Startcell, Startcell.SpecialCells(xlCellTypeLastCell))
Set DestSheet = ThisWorkbook.Worksheets("Data")
Set dest = DestSheet.Cells(DestSheet.Rows.Count, 1).End(xlUp).Offset(1, 0)
'set dest to next blank row
Source.Copy dest
Set dest = DestSheet.Range(dest, dest.SpecialCells(xlCellTypeLastCell))
dest.Sort key1:=dest.Cells(1, 1)
'sort to shift blanks to bottom
End Sub
finally surfing in stackoverflow I found a pice of code that do exactly want I need, so final macro looks like this:
Sub CopyTable()
Dim lastVal As Range, sht As Worksheet
Set sht = Sheets("Form")
Set lastVal = sht.Columns(2).Find("*", sht.Cells(1, 2), xlValues, _
xlPart, xlByColumns, xlPrevious)
Debug.Print lastVal.Address
sht.Range("A9", lastVal).Resize(, 26).Select 'select B:Ag
Selection.Copy
Sheets("Data").Select
Range("A1").Select
Do While Not IsEmpty(ActiveCell)
ActiveCell.Offset(1, 0).Select
Loop
ActiveCell.Offset(0, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
End Sub

Move/Paste code not responding properly

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

Excel VBA - Do Until Blank Cell

I'm recording a macro and need some help. I'd like copy and paste the values from the column G of the "SalesData" worksheet into cells A2, A12, A22 etc of the "Results" worksheet until there's no more values in the column G.
VBA is pretty new to me, I've tried using Do/Until, but everything crashed. Could you please help me? Please see the code I've recorded below. Thank you!
Sub(x)
Sheets("SalesData").Select
Range("G2").Select
Selection.Copy
Sheets("Results").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A12").Select
Sheets("SalesData").Select
Range("G3").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Results").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A22").Select
Sheets("SalesData").Select
Range("G4").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Results").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A32").Select
Sheets("SalesData").Select
Range("G5").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Results").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
I prefer to find the last cell in the column first then use a For loop.
Since you are only doing the values we can avoid the clipboard and assign the values directly.
Since you paste is every 10 cells we can use a separate counter to move down 10 each loop.
Sub x()
Dim ws As Worksheet
Dim lst As Long
Dim i As Long, j As Long
'use variable to limit the number of times we type the same thing
Set ws = Worksheets("Results")
'First row of the output
j = 2
'using with and the "." in front of those items that belong to it also limits the typing.
With Worksheets("SalesData")
'Find the last row with values in Column G
lst = .Cells(.Rows.Count, 7).End(xlUp).Row
'Loop from the second row to the last row.
For i = 2 To lst
'Assign the value
ws.Cells(j, 1).Value = .Cells(i, 7).Value
'Move down 10 rows on the output
j = j + 10
Next i
End With
End Sub
here is the same thing but using range variables
Sub x()
Dim src As Range
Dim dst As Range
Set dst = Worksheets("Results").Range("a2") ' point to top cell of destination
With Worksheets("SalesData")
For Each src In Range(.Cells(2, "g"), .Cells(.Rows.Count, "g").End(xlUp)) ' loop through used cell range in column G
dst.Value = src.Value
Set dst = dst.Offset(10) ' move destination pointer down 10 rows
Next src
End With
End Sub
This is just for fun/practice for another way to do it:
Sub copyFromG()
Dim copyRng As Range, cel As Range
Dim salesWS As Worksheet, resultsWS As Worksheet
Set salesWS = Sheets("SalesData")
Set resultsWS = Sheets("Results")
Set copyRng = salesWS.Range("G2:G" & salesWS.Range("G2").End(xlDown).Row) ' assuming you have a header in G1
For Each cel In copyRng
resultsWS.Range("A" & 2 + 10 * copyRng.Rows(cel.Row).Row - 30).Value = cel.Value
Next cel
End Sub

'Range' of Object ' _Global' failed error when selectng range

I'm really new to programming in VBA and having a problem with this code I'm trying to write. I am wanting the code to figure out the first row in column A that is unused then copy and paste data from a different part of the sheet into that row.
Sub CopyandPaste()
Dim RowLast As Long
RowLast = ThisWorkbook.Worksheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).Row
Set NewRange = ThisWorkbook.Worksheets("Sheet2").Cells(RowLast, 1)
ThisWorkbook.Worksheets("Sheet1").Cells(8, "B").Select
Selection.Copy
Range("NewRange").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
Any help would be extremely helpful.
Try this code :
Sub CopyandPaste()
Dim RowLast As Long
ThisWorkbook.Activate
With Worksheets("Sheet2")
RowLast = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Row
Sheets("Sheet1").Cells(8, "B").Copy Sheets("Sheet2").Cells(RowLast, 1)
End With
End Sub
I have added comments into the code explaining changes I made.
Sub CopyandPaste()
Dim RowLast As Long
Dim newRange As Range
'this works easier if I understand your intent right
'I generally use some large row number with Excel 2010
'You may ahve to make this smaller if you are in 03
RowLast = Sheets("Sheet2").Range("B99999").End(xlUp) + 1
'if you KNOW you have continuous data in this column (no spaces)
RowLast = Sheets("Sheet2").Range("B1").End(xldown) + 1
'this is slightly better way to do this
Set newRange = ThisWorkbook.Worksheets("Sheet2").Range("A" & RowLast)
'don't do this
'ThisWorkbook.Worksheets("Sheet1").Cells(8, "B").Select
'Selection.Copy
'do this instead
Sheets("Sheet1").Range("B8").Copy
newRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'you were attempting to use a variable name (newrange) as a
'name of a named range in the Excel sheet
'use the variable range itself (as above)
End Sub