Copy one cell and paste down a column - vba

Been trying to figure out how to copy a cell from worksheet A and paste it down a column in Worksheet B until it matches the same amount of rows as an adjacent column. Take the following screenshot for example. How would I properly accomplish this in VBA? Been trying to figure this out for a while now. All I've been able to do is copy the cell and paste it adjacent to the last cell in the adjacent column instead of down the entire column. The worksheet I'm copying data from is pictured below.
Copy From SpreadSheet down below
Paste to SpreadSheet down below
Current Code
Sub pullSecEquipment()
Dim path As String
Dim ThisWB As String
Dim wbDest As Workbook
Dim shtDest As Worksheet
Dim shtPull As Worksheet
Dim Filename As String
Dim Wkb As Workbook
Dim CopyRng As Range, DestRng As Range
Dim lRow As Integer
Dim destLRow As Integer
Dim Lastrow As Long
Dim FirstRow As Long
Dim UpdateDate As String
ThisWB = ActiveWorkbook.Name
Dim selectedFolder
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
selectedFolder = .SelectedItems(1) & "\"
End With
path = selectedFolder
Application.EnableEvents = False
Application.ScreenUpdating = False
Set shtDest = Workbooks("GPnewchapterTEST2.xlsm").Worksheets("START")
'clear content of destination table
shtDest.Rows("8:" & Rows.Count).ClearContents
Filename = Dir(path & "\*.xls*", vbNormal)
If Len(Filename) = 0 Then Exit Sub
Do Until Filename = vbNullString
Set Wkb = Workbooks.Open(Filename:=path & "\" & Filename)
'MsgBox Filename
'''''
'SEC
'''''
If InStr(Filename, "Equipment") <> 0 Then
Dim range1 As Range
Set range1 = Range("E:K")
'For Each Wkb In Application.Workbooks
'For Each shtDest In Wkb.Worksheets
'Set shtPull = Wkb.Sheets(1)
'If shtPull.Name Like "*-*" Then
'last row
destLRow = Wkb.Sheets(1).Cells.Find(what:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row
'1st row
lRow = Wkb.Sheets(1).Cells.Find(what:="EQUIPMENT DESCRIPTION", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
'STHours
Dim i As Integer
For i = lRow To destLRow
Set CopyRng = Wkb.Sheets(1).Range(Cells(i, 5).Address, Cells(i, 11).Address)
Set DestRng = shtDest.Range("O" & shtDest.Cells(Rows.Count, "O").End(xlUp).Row + 1)
CopyRng.Copy
DestRng.PasteSpecial Transpose:=True
Application.CutCopyMode = False 'Clear Clipboard
Set CopyRng = Wkb.Sheets(1).Range(Cells(i, 1).Address, Cells(i, 1).Address)
Set DestRng = shtDest.Range("C" & shtDest.Cells(Rows.Count, "O").End(xlDown).Row)
CopyRng.Copy
DestRng.PasteSpecial Transpose:=True
Application.CutCopyMode = False 'Clear Clipboard
Set CopyRng = Wkb.Sheets(1).Range(Cells(i, 3).Address, Cells(i, 3).Address)
Set DestRng = shtDest.Range("S" & shtDest.Cells(Rows.Count, "O").End(xlUp).Row)
CopyRng.Copy
DestRng.PasteSpecial Transpose:=True
Application.CutCopyMode = False 'Clear Clipboard
i = i + 2
Next i
'Dim cell As Integer
'Dim empname As String
'destLRow = 8 '' find out how to find first available row
'For cell = 2 To lRow
'empname = Wkb.Sheets(1).Cells(cell, 3).Value & " " & Wkb.Sheets(1).Cells(cell, 4).Value
' shtDest.Cells(8, 5).Value = empname
'shtDest.Cells(8, 1).Value = "Service Electric"
'Next cell
' Wkb.Close Save = False
End If
'End If
Filename = Dir()
Loop
MsgBox "Done!"
End Sub

if you want to do in VBA and want to copy one value in "ALL" column
Cells(1,1).Copy Columns(1)

Related

How can I copy the range like ctrl+A in VBA

I got a problem with copying the range of cells. Usually I used to make it with activecell method. But in current situation it doesn't work. I mean the code does not select the whole range of cells. How can I apply CTRL+A excel shortcut to VBA?
Sub MergeDifferentWorkbooksTogether()
Dim wbk As Workbook
Dim wbk1 As Workbook
Dim Filename As String
Dim Path As String
Dim D As Date
D = Date - 3
Workbooks.Add
ActiveWorkbook.SaveAs "C:\Users\xezer.suleymanov\Desktop\Summary & D"
Set wbk1 = Workbooks("Summary & D")
Path = "\\FILESRV\File Server\Hesabatliq\Umumi\Others\Branchs' TB\Branchs' TB as of 2018\" & D
Filename = Dir(Path & "\*.xlsx")
Do While Len(Filename) > 0
Set wbk = Workbooks.Open(Path & "\" & Filename)
wbk.Activate
Range("A6").Value = "Branch Name"
Range("B1").Copy
Range("B6").End(xlDown).Offset(0, -1).Activate
Range(ActiveCell, ActiveCell.End(xlUp).Offset(1, 0)).Select
Selection.PasteSpecial xlPasteAll
Application.CutCopyMode = False
Range("A6").Activate
Range(ActiveCell, ActiveCell.End(xlToRight).End(xlDown)).Copy
wbk1.Activate
Application.DisplayAlerts = False
wbk1.Sheets("Sheet1").Range("A1048576").End(xlUp).Offset(1, 0).Select
ActiveCell.PasteSpecial xlPasteAll
wbk.Close True
Filename = Dir
Loop
End Sub
You may try something like this...
Dim lr As Long, lc As Long
Dim rng As Range
lr = Cells(Rows.Count, 1).End(xlUp).Row
lc = Cells(6, Columns.Count).End(xlToLeft).Column
Set rng = Range("A6", Cells(lr, lc))
rng.Copy
Also, if row5 is blank, you may also try...
Range("A6").CurrentRegion.Copy

Loop not working between directories

I worked around with a vba code to search a list of cells in a column of a workbook and those cells need to be searched in a folder and if cell is matched in any of the workbook all corresponding data needs to be copied to the main workbook.
I was working with 2 loops but if one is working another one is not for example if I loop through all files in a folder I can't loop with the column in the main workbook to search one cell after another.
Below is the code:
Sub SearchFolders()
Dim fso As Object
Dim fld As Object
Dim strSearch As String
Dim strPath As String
Dim strFile As String
Dim wOut As Worksheet
Dim wbk As Workbook
Dim wks As Worksheet
Dim rFound As Range
Dim irow As Integer
Dim rng As Range
Dim strFirstAddress As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
strPath = "\dfs\Home\Tes"
Set wOut = ThisWorkbook.Worksheets("Data")
With wOut
lRow = 2
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.GetFolder(strPath)
strFile = Dir(strPath & "\*.xls*")
Do While Cells(lRow, 1) < Empty
strSearch = Cells(lRow, 1)
Set wbk = Workbooks.Open _
(Filename:=strPath & "\" & strFile, _
UpdateLinks:=0, _
ReadOnly:=True, _
AddToMRU:=False)
For Each wks In wbk.Worksheets
Set rFound = wks.UsedRange.Find(strSearch)
If Not rFound Is Nothing Then
strFirstAddress = rFound.Address
End If
Do
If rFound Is Nothing Then
Exit Do
Else
Cells(lRow, 2) = rFound.Offset(0, 1).Value
Cells(lRow, 3) = rFound.Offset(0, 2).Value
End If
Set rFound = wks.Cells.FindNext(After:=rFound)
Loop While strFirstAddress < rFound.Address
Next
wbk.Close (False)
lRow = lRow + 1
Loop
End With
MsgBox "Done"
End Sub
I think you have to change the do while to
Do While .Cells(lRow, 1) <> Empty
Explanation: If you use Cells(lRow, 1) (without dot), you access the active sheet. But in the moment you do a workbook.open, the active sheet will change, so at the next iteration you no longer look to the sheet wOut but to a sheet of the opened wokbook.
If you write .Cells(lRow, 1) (with leading dot), Cells is seen as a property of whatever you have used in a with-clause, in your case With wOut. Alternatively, you could write wOut.Cells(lRow, 1) (this is just a matter of taste)

Excel VBA to summarize last cell of certain column to 'summary' worksheet

I am trying to summarize worksheets (invoices) into "Summary-Sheet" using below code that I found Internet. I am unsuccessfully trying to modify it to select last cell in column F (total amount) which represents total of each invoice.
Total in column F has varying row number based on items sold.
Please help me in updating code to it select total amount from last cell having value in column F.
Thank you!
Sub Summary_All_Worksheets_With_Formulas()
Dim Sh As Worksheet
Dim Newsh As Worksheet
Dim myCell As Range
Dim ColNum As Integer
Dim RwNum As Long
Dim Basebook As Workbook
With Application
.Calculation = xlCalculationManual
.ScreenUpdating = False
End With
'Delete the sheet "Summary-Sheet" if it exist
Application.DisplayAlerts = False
On Error Resume Next
ThisWorkbook.Worksheets("Summary-Sheet").Delete
On Error GoTo 0
Application.DisplayAlerts = True
'Add a worksheet with the name "Summary-Sheet"
Set Basebook = ThisWorkbook
Set Newsh = Basebook.Worksheets.Add
Newsh.Name = "Summary-Sheet"
'The links to the first sheet will start in row 2
RwNum = 1
For Each Sh In Basebook.Worksheets
If Sh.Name <> Newsh.Name And Sh.Visible Then
ColNum = 1
RwNum = RwNum + 1
'Copy the sheet name in the A column
Newsh.Cells(RwNum, 1).Value = Sh.Name
For Each myCell In Sh.Range("A1,A2,C3,E3,C4,E4,C5,E5") '<--Change the range
ColNum = ColNum + 1
Newsh.Cells(RwNum, ColNum).Formula = _
"='" & Sh.Name & "'!" & myCell.Address(False, False)
Next myCell
End If
Next Sh
Newsh.UsedRange.Columns.AutoFit
With Application
.Calculation = xlCalculationAutomatic
.ScreenUpdating = True
End With
End Sub
You do not need to loop through the cells to find your "total amount". I modified part of your code as follows:
If Sh.Name <> Newsh.Name And Sh.Visible Then
ColNum = 1
RwNum = RwNum + 1
'Copy the sheet name in the A column
Newsh.Cells(RwNum, 1).Value = Sh.Name
'put this declaration on top
Dim CellsArray() As String
Dim RangeString As String
Dim intCount As Integer
'your collection of ranges
RangeString = "A1,A2,C3,E3,C4,E4,C5,E5"
'split them into array
CellsArray = Split(RangeString, ",")
'loop through your array
For intCount = LBound(CellsArray) To UBound(CellsArray)
ColNum = ColNum + 1
Newsh.Cells(RwNum, ColNum).Formula = _
"='" & Sh.Name & "'!" & CellsArray(intCount) '<- access each range in array
Next intCount
'Find last row in the column: "Total Amount"
LastRow = Sh.Cells(Sh.Rows.Count, "F").End(xlUp).Row
'Assign that cell to myCell
Set myCell = Sh.Range("F" & LastRow)
'total
ColNum = ColNum + 1
Newsh.Cells(RwNum, ColNum).Formula = _
"='" & Sh.Name & "'!" & myCell.Address(False, False)
End If
Edit: I added the loop cycle in the middle as requested

VBA - Vlookup returns on development but not when added to ribbon

I've a strange problem.
the following code will run using F8 or pressing the run button on the development module.
But when added to the excel ribbon as a macro by the following process the vlookup will return #N/A :
1.right click on the excel toolbar > customize the ribbon
choose macro commands
add it to a new group.
the code is :
Sub Compare()
'set primary Workbook
'find last cell'
Dim WS As Worksheet
Dim LastCell As Range
Dim LastCellRowNumber As Long
Set WS = Worksheets("Sheet1")
With WS
Set LastCell = .Cells(.Rows.Count, "A").End(xlUp)
LastCellRowNumber = LastCell.Row
'MsgBox (LastCell.Row)
End With
'Adding Index Column
Columns("A:A").Select
Selection.Insert Shift:=xlToRight
[A2].Formula = "=G2&H2"
Range("A2:A" & LastCellRowNumber).FillDown
'adding headers
[Ag1].Value = "Resale"
[Ah1].Value = "Cost"
[Ai1].Value = "disti"
'set primary Workbook
Dim Pri As Workbook
Set Pri = ActiveWorkbook
'open company quotes
Workbooks.Open ("R:\company\DATA\company quotes.xlsx")
'find last cell'
Dim WSq As Worksheet
Dim LastCellq As Range
Dim LastCellRowNumberq As Long
Set WSq = Worksheets("Quote Summary")
With WSq
Set LastCellq = .Cells(.Rows.Count, "A").End(xlUp)
LastCellRowNumberq = LastCellq.Row
'MsgBox (LastCell.Row)
End With
Columns("A:A").Select
Selection.Insert Shift:=xlToRight
Dim quotes As Workbook
Set quotes = ActiveWorkbook
[A2].Formula = "=J2&B2"
Range("A2:A" & LastCellRowNumberq).FillDown
Pri.Activate
Dim i As Integer
For i = 2 To LastCellRowNumber
Dim result As String
Dim sheet As Worksheet
Range("AG" & i) = Application.VLookup(Sheet1.Range("A" & i), Workbooks("company quotes.xlsx").Worksheets("Quote Summary").Range("A2:AS" & LastCellRowNumberq), 17, False)
Range("AH" & i) = Application.VLookup(Sheet1.Range("A" & i), Workbooks("company quotes.xlsx").Worksheets("Quote Summary").Range("A2:AS" & LastCellRowNumberq), 19, False)
Range("Ai" & i) = Application.VLookup(Sheet1.Range("A" & i), Workbooks("company quotes.xlsx").Worksheets("Quote Summary").Range("A2:AS" & LastCellRowNumberq), 20, False)
Next i
End Sub
I've tried to fix any referencing issues I could find but you'll need to have a look through and make sure all of the Range references are prefixed with the correct Workbook and Worksheet as it wasn't too clear which worksheet they were coming from in the original code:
Sub Compare()
'Set primary Workbook
'Find last cell
Dim WS As Worksheet
Dim LastCellRowNumber As Long
Set WS = ThisWorkbook.Sheets("Sheet1")
LastCellRowNumber = WS.Cells(WS.Rows.Count, "A").End(xlUp).Row
'MsgBox (LastCell.Row)
'Adding Index Column
WS.Columns("A:A").Insert Shift:=xlToRight
WS.Range("A2:A" & LastCellRowNumber).Formula = "=G2&H2"
'adding headers
WS.Range("AG1").Value = "Resale"
WS.Range("AH1").Value = "Cost"
WS.Range("AI1").Value = "disti"
'open company quotes
Dim wbCompQuotes As Workbook
Set wbCompQuotes = Workbooks.Open ("R:\company\DATA\company quotes.xlsx")
'find last cell'
Dim wsQuoteSum As Worksheet
Dim LastCellRowNumberq As Long
Set wsQuoteSum = wbCompQuotes.Worksheets("Quote Summary")
LastCellRowNumberq = wsQuoteSum.Cells(wsQuoteSum.Rows.Count, "A").End(xlUp).Row
'MsgBox (LastCell.Row)
wsQuoteSum.Columns("A:A").Insert Shift:=xlToRight
wsQuoteSum.Range("A2:A" & LastCellRowNumberq).Formula = "=J2&B2"
Dim i As Long
For i = 2 To LastCellRowNumber
WS.Range("AG" & i) = Application.VLookup(WS.Range("A" & i), wsQuoteSum.Range("A2:AS" & LastCellRowNumberq), 17, False)
WS.Range("AH" & i) = Application.VLookup(WS.Range("A" & i), wsQuoteSum.Range("A2:AS" & LastCellRowNumberq), 19, False)
WS.Range("AI" & i) = Application.VLookup(WS.Range("A" & i), wsQuoteSum.Range("A2:AS" & LastCellRowNumberq), 20, False)
Next i
End Sub

Pasting between workbooks excel vba

i have 50 workbooks and i made a code to copy from a main one the rows in which are the corespondent names to the other 49 files. the problem is in pasting to the 49 target files - paste method doesn't work. The errors is when the filter doesn't find entries for a name. How can i include a line that if the filter doesn't find a name in the main file, it will paste "no entries this month" in the file with the name that wasn't find? Thank you.
Any help is welcomed.
Sub name1()
Dim ws As Worksheet
Dim rng As Range, rngA As Range, rngB As Range
Dim LRow As Long
Set ws = Sheets("name list")
With ws
LRow = .Range("A" & .Rows.Count).End(xlUp).Row
Set rng = .Range("A1:M" & LRow)
.AutoFilterMode = False
With rng
.AutoFilter Field:=12, Criteria1:="name1"
Set rngA = .Offset(1, 0).SpecialCells(xlCellTypeVisible)
End With
.AutoFilterMode = False
With rng
.AutoFilter Field:=13, Criteria1:="name1"
Set rngB = .Offset(1, 0).SpecialCells(xlCellTypeVisible)
End With
.AutoFilterMode = False
rng.Offset(1, 0).EntireRow.Hidden = True
Union(rngA, rngB).EntireRow.Hidden = False
End With
End Sub
Sub name11()
Dim lst As Long
Dim rng As Range
Dim i As Integer
Set rng = Application.Intersect(ActiveSheet.UsedRange, Range("A:M"))
rng.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
Application.DisplayAlerts = False
Workbooks.Open Filename:= _
"\\HOFS\persons\name1.xlsm" _
, UpdateLinks:=true
With Sheets("tribute").Range("A" & Rows.Count).End(xlUp).Offset(1)
'.PasteSpecial Paste:=xlPasteColumnWidths
.PasteSpecial Paste:=xlPasteValues
End With
ActiveWorkbook.Close SaveChanges:=True
Application.DisplayAlerts = False
Windows("name list.xlsm").Activate
rng.Offset(1, 0).EntireRow.Hidden = False
End Sub
Sub TRANSFER_name1()
Call name1
Call name11
End Sub
Set the last row separately.
' Gives the first empty row in column 1 (A)
lastRow = Worksheets("tribute").Cells(Worksheets("tribute").Rows.Count, 1).End(xlUp).Row + 1
' Pastes values
Worksheets("tribute").Range("A" & lastRow).PasteSpecial Paste:=xlPasteValues
Its probably much better to avoid copy/paste situations. This can get super time consuming over time.
try somethign like this instead:
With Sheets("tribute").Range("A" & Rows.Count).End(xlUp).Offset(1).value = rng.Value
This is a bit crude but I am sure you can significantly simplify your code if you do.
Dim wbk As Workbook
Dim Filename As String
Dim path As String
Dim rCell As Range
Dim rRng As Range
Dim wsO As Worksheet
Dim StartTime As Double
Dim SecondsElapsed As Double
Dim sheet As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
StartTime = Timer
path = "pathtofolder" & "\"
Filename = Dir(path & "*.xl??")
Set wsO = ThisWorkbook.Sheets("Sheet1")
Do While Len(Filename) > 0
DoEvents
Set wbk = Workbooks.Open(path & Filename, True, True)
Set rRng = sheet.Range("b1:b308")
For Each rCell In rRng.Cells
wsO.Cells(wsO.Rows.count, 1).End(xlUp).Offset(1, 0).Value = rCell
Next rCell
wbk.Close False
Filename = Dir
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Calculation = xlCalculationAutomatic
SecondsElapsed = Round(Timer - StartTime, 2)
MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation