I am trying to create a VBA module, that takes data from a table in one worksheet and copies it to a second worksheet. This second worksheet should then be exported as a PDF.
The exporting part and naming the PDF is not an issue and I will only tackle this when the copying of the data from one sheet to the other works.
The structure of the table is that I have several rows that have data relevant to the invoice I want to fill on the second sheet and I would like that the macro loops through the whole file and only takes what it needs, but for now I am working on an easier version where I simply want to copy the data from a selection.
Option Explicit
Sub InvoiceCreator()
'create sheet
'Add info to sheet'
'save invoice sheet as PDF with name of customer
'reset sheet
'insert i+1 dataset
'loop til end
Dim sWS As Worksheet
Dim dWS As Worksheet
Dim sRange As Range
Dim sBNR As Range
Dim dBNR As Range
Dim sKNR As Range
Dim dKNR As Range
Dim sREF As Range
Dim dREF As Range
Dim sPRT As Range
Dim dPRT As Range
Dim sDAT As Range
Dim dDAT As Range
Dim sADR As Range
Dim dADR As Range
Dim sDES As String
Dim dDES As String
'Dim sPRC As Range
'Dim dPRC As Range
Dim i As Integer
Dim lastrow As Long
Set sWS = Sheets("Data")
Set dWS = Sheets("Sheet1")
Set sRange = Selection
Set sBNR = sRange.Cells(2, 7)
Set dBNR = dWS.Range("E4")
dBNR = sBNR.Value
Set sKNR = sRange.Cells(2, 2)
Set dKNR = dWS.Range("E6")
dKNR = sKNR.Value
Set sREF = sRange.Cells(2, 22)
Set dREF = dWS.Range("E8")
dREF = sREF.Value
Set sPRT = sRange.Cells(2, 23)
Set dPRT = dWS.Range("E10")
dPRT = sPRT.Value
Set sDAT = sRange.Cells(2, 4)
Set dDAT = dWS.Range("F4")
dDAT = sDAT.Value
lastrow = sRange.End(xlUp).Row
For i = 2 To lastrow
sDES = sRange.Cells(i, 12)
dDES = dWS.Range("A" & i + 23)
dDES = sDES
Next i
End Sub
Most of the code works and copies values from one sheet to the other, but I am stuck with the last loop bit.
I want to take the value of the string in a cell and copy it to a cell in the other sheet and then copy the cell value of the cell below and copy it to the other worksheet one cell below until the end of my selection. I am not getting any error, but it is not copying the data.
Any advice?
Related
I am trying to select a subset of data in a range and copy it to another sheet in Excel. My thought process was as follows
Find the first and last instance of the value in a column
Copy from the first instance down to the last instance and all the way to the Right
Paste the range of data into my sheet
I am having trouble finding the first and last instance of the value in a column and setting the range to copy.
This is what I have so far:
Sub Button()
'Application.ScreenUpdating = False
Dim wb As Workbook
Dim ws_temp, ws_data As Worksheet
Dim data_rng As Range
Set wb = ThisWorkbook
Set ws_temp = wb.Sheets("Template")
Set ws_data = wb.Sheets("data")
'declare id
Dim id As Integer
Set id= ws_temp.Range("B4").Value 'this is where the value is stored
'find first instance of id in data.
' The data starts in cell A6 and extends to column O. The number of rows will be variable
'find last instance of pitcher id
'Set data_rng
Set data_rng = wb.ws_data.Range("first instance":O&"second instance")
'Copy data_rng
data_rng.Copy wb.ws_temp.Range("A8") 'the data will always go in cell A8 on the Template sheet
'Application.ScreenUpdating = True
End Sub
What you could do is use Application.Match to find the row of the first instance then use Application.CountIf to count the no of occurrences of the search term.
With that information you should be able to get the subset of the data you want to copy using Resize.
Sub Button()
Dim wb As Workbook
Dim ws_temp, ws_data As Worksheet
Dim data_rng As Range
Dim id As Long
Dim lngFirstRow As Long
Dim lngNoRows As Long
Application.ScreenUpdating = False
Set wb = ThisWorkbook
Set ws_temp = wb.Sheets("Template")
Set ws_data = wb.Sheets("data")
' get search id
id = ws_temp.Range("B4").Value
' find row of first occurence of id
lngFirstRow = Application.Match(id, ws_data.Columns(2), 0)
' find count of id
lngNoRows = Application.CountIf(ws_data.Columns(2), id)
Set data_rng = ws_data.Range("B" & lngFirstRow).Resize(lngNoRows, 14)
'Copy data_rng
data_rng.Copy ws_temp.Range("A8") 'the data will always go in cell A8 on the Template sheet
Application.ScreenUpdating = True
End Sub
I have a large sheet of data:
Updated Data
where i need to copy only a speacific part of this data to another worksheet:
The data i need to copy is always 4 cells wide however can be at any row and column. The first column cell at the top will allways be the same text value and i need to copy then from that found cell, 4 cells across to the right and then down to the cells are empty. All subsequent ranges after the first will use the same columns have several empty cells bother above and below each range needed. The macro will be run using a "button" so doesn't need to be checking the value of the cell all the time. The images are simplified versions of the data but are very accurate. 0 is used to show data surrounding range, HELLO is the data inside the range and INT_EXT_DOOR is my searched for cell value which can be in any column between data sets but will be the same inside each data set. The first range always starts at row 2.
Each range has to be numbered, defined by another worksheets cell value. For example, if my cell value is 1 i need it to copy range 1, if my value is 2 copy range 2 ect.
I have been trying to no luck to get anything that works like needed and would appreciate any help, thanks.
Test the next function, please:
Private Function testReturnBlock(strBlock As String, blkNo As Long)
Dim sh As Worksheet, ws As Worksheet, lastRow As Long, searchC As Range
Dim rng As Range
Set sh = ActiveSheet ' use here your sheet to be processed
Set ws = Worksheets("Return") 'use here your sheet where the data will be returned
Set searchC = sh.UsedRange.Find(strBlock)
If searchC Is Nothing Then MsgBox "No such a field in the worksheet...": Exit Function
lastRow = sh.Cells(Rows.Count, searchC.Column).End(xlUp).row
'The following part works well only if the blocks are separated by empty rows, as you said it is your sheet data case...
Set rng = sh.Range(searchC, sh.Cells(LastRow, searchC.Column)).SpecialCells(xlCellTypeConstants)
ws.Range("A1").Resize(rng.Areas(blkNo).Rows.Count, 4).Value = rng.Areas(blkNo).Resize(, 4).Value
End Function
The above function should be called like this:
Sub testRetBlock()
testReturnBlock "INT_EXT_DOOR", 2
End Sub
But in order to see that the correct range has been returned, you must adapt them in a way (in your test sheet), do differentiate. I mean the second one to contain "HELLO1" (at least on its first row), the following "HELLO2" and so on...
Try this routine if it does what you need. otherwise it should be a good start for adding whatever you need on top.
Option Explicit
Sub CopyBlock()
Dim wb As Excel.Workbook
Dim wsSource As Excel.Worksheet
Dim wsDest As Excel.Worksheet
Dim wsSelect As Excel.Worksheet
Dim lBlockNo As Long
Dim strCellID As String
Dim lBlock As Long
Dim lRow As Long
Dim lBlockRow As Long
Dim lBlockCol As Long
Dim searchRange As Excel.Range
Dim bRange As Excel.Range
Dim cRange As Excel.Range
Set wb = ActiveWorkbook
' set the worksheet objects
Set wsSource = wb.Sheets("Source")
Set wsDest = wb.Sheets("Dest")
Set wsSelect = wb.Sheets("Select") ' here you select which block you want to copy
' Identifier String
strCellID = "INT_EXT_DOOR"
' Which block to show. We assume that the number is in cell A1, but could be anywhere else
lBlockNo = wsSelect.Range("A1")
lRow = 1
' Find block with lBlockNo
For lBlock = 1 To lBlockNo
' Search the identifier string in current row
Do
lRow = lRow + 1
Set searchRange = wsSource.Rows(lRow)
Set bRange = searchRange.Find(strCellID, LookIn:=xlValues)
Loop While (bRange Is Nothing)
Next lBlock
lBlockRow = bRange.Row
lBlockCol = bRange.Column
' Search the first with empty cell
Do
lRow = lRow + 1
Loop While wsSource.Cells(lRow, lBlockCol) <> ""
' Copy the range found into the destination sheet
Range(Cells(lBlockRow, lBlockCol), Cells(lRow - 1, lBlockCol + 3)).Copy wsDest.Range("A1")
' Note the block copied
wsDest.Cells(1, 6) = "Block No:"
wsDest.Cells(1, 8) = lBlockNo
' Clean up (not absolutely necessary, but good practice)
Set searchRange = Nothing
Set bRange = Nothing
Set cRange = Nothing
Set wsSource = Nothing
Set wsDest = Nothing
Set wsSelect = Nothing
Set wb = Nothing
End Sub
Let me know if you need more help
I'm using the following string to copy a column from one sheet to another
Dim wsCore As Worksheet
Dim wsData As Worksheet
Set wsCore = Sheets("R2 Data Dump")
Set wsData = Sheets("Active")
Dim rowNumber As Integer
Dim cellFormulas As Variant
Dim cellFormulas1 As Variant
Dim counter As Integer
counter = 0
Dim currentCell As String
Dim importSheetCell As Variant
Dim importSheetOffset As Variant
Dim contractnum As Integer
Dim pt As PivotTable
Dim ws As Worksheet
Dim pc As PivotCache
Dim lastrow As Long
Set wsCore = Sheets("R2 Data Dump")
Set wsData = Sheets("Active")
Sheets("R2 Data Dump").Visible = True
Sheets("R2 Data Dump").Select
rowNumber = ActiveSheet.UsedRange.Rows.Count
With wsCore
Startrow = 3
wsCore.Columns("W").Copy Destination:=wsData.Columns("A")
wsCore.Columns("B").Copy Destination:=wsData.Columns("B")
wsCore.Columns("C").Copy Destination:=wsData.Columns("C")
wsCore.Columns("D").Copy Destination:=wsData.Columns("D")
End With.
So what is does is copy the particular columns from one sheet and paste it on the specified column of the destination sheet. My problem is, the action starts pasting the copied cell from the source sheet to the first row on the destination cell. What I would like to find out is how can I set a row number where it would start pasting instead of row 1.
Typically, you would go to the first blank cell in the column (looking from the bottom up).
With Intersect(wsCore.Columns("A:W"), wsCore.UsedRange)
.Columns("W").Copy Destination:=wsData.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
.Columns("B").Copy Destination:=wsData.Cells(Rows.Count, "B").End(xlUp).Offset(1, 0)
.Columns("C").Copy Destination:=wsData.Cells(Rows.Count, "C").End(xlUp).Offset(1, 0)
.Columns("D").Copy Destination:=wsData.Cells(Rows.Count, "D").End(xlUp).Offset(1, 0)
End With
If you wanted to specify a row, declare a long variable and use that.
Dim rw As Long
rw = 10
With Intersect(wsCore.Columns("A:W"), wsCore.UsedRange)
.Columns("W").Copy Destination:=wsData.Cells(rw, "A")
.Columns("B").Copy Destination:=wsData.Cells(rw, "B")
.Columns("C").Copy Destination:=wsData.Cells(rw, "C")
.Columns("D").Copy Destination:=wsData.Cells(rw, "D")
End With
I've used Intersect to guard against trying to copy a full column into a column that doesn't start at the first row. A full column won't fit.
I found code similar to the following where the data from one workbook is moved to another by using a loop. The code works except for the information that it moves is incorrect. Could someone tell me why it keeps copying the last column X number of times (where X = number of rows)? I want to copy the data between A2 and J11 only once instead of X rows of J2 and X rows of J3, and so on.
Sub CopySample()
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim lCol As Range, lRow As Range
Dim CurCell_1 As Range, CurCell_2 As Range
Application.ScreenUpdating = False
'~~> Change as applicable
Set wb1 = Workbooks("Sample1.xlsm")
Set wb2 = Workbooks("OverallData_Month_X.xlsm")
Set ws1 = wb1.Sheets("SampleSheet")
Set ws2 = wb2.Sheets("All Cylinders Data") '<~~ Change as required
For Each lCol In ws1.Range("A2:J11")
'~~> Why this?
Set CurCell_2 = ws2.Range("A2:J2")
For Each lRow In ws1.Range("A2:J11")
Set CurCell_1 = ws1.Cells(lRow.Row, lCol.Column)
If Not IsEmpty(CurCell_1) Then
CurCell_2.Value = CurCell_1.Value
Set CurCell_2 = CurCell_2.Offset(1)
End If
Next
Next
Application.ScreenUpdating = True
End Sub
Untested, but try changing this line Set CurCell_2 = ws2.Range("A2:J2") to :
Set CurCell_2 = ws2.Cells(1, lCol.Column)
UPDATE
Overall it seems that the above code is setting it's references to different sections of the workbook, and offsetting (moving) those references. I'd argue that there are more efficant ways to do this, and easier ways to code it as well. so while the above answer only solved half of the problems you were having, i've rewritten your code below so that it'll hopefully make more sence to you for you to understand + update.
I believe the below code example does what you're trying to accomplish:
(comments in code)
Sub CopySample
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Set wb1 = Workbooks("Sample1.xlsm")
Set wb2 = Workbooks("OverallData_Month_X.xlsm")
Set ws1 = wb1.Sheets("SampleSheet")
Set ws2 = wb2.Sheets("All Cylinders Data")
Dim rngCopyFromRange As Range
Set rngCopyFromRange = ws1.Range("A2:J11") '- name the copy range for ease of read
Dim rngPasteStartCell As Range
Set rngPasteStartCell = ws2.Range("A2") 'top left cellt o begin the paste
Dim lCurrentColumn As Long
Dim lCurrentRow As Long
For lCurrentColumn = 1 To rngCopyFromRange.Columns.Count 'for each column in the source data
For lCurrentRow = 1 To rngCopyFromRange.Rows.Count '-for each row in each column in source data
'set the offset of the starting cell's value equal ot the top left cell in the source data offset by the same amount
'- where the offsets are equal to the row/column we are on - 1
rngPasteStartCell.Offset(lCurrentRow - 1, lCurrentColumn - 1).Value = _
rngCopyFromRange.Cells(1, 1).Offset(lCurrentRow - 1, lCurrentColumn - 1).Value
Next lCurrentRow
Next lCurrentColumn
End Sub
Below is the code I have so far. I am trying to do the following:
Compare the "ICT number" to the name of worksheet and if that worksheet name contains the ICT number, even if it is mixed in with other string values, then i want to look at a certain cell in that worksheet and compare the value in that cell with a cell in my checklist worksheet.
If those values are the same, then i want to have a message come up in a corresponding cell on that row saying that the two sources reconcile.
I then want this to loop for all of the rows in the checklist worksheet and all of the worksheets in the workbook.
Dim ICT_Number As Range
Dim statmentdata As Range
Dim checklistdata As Range
Dim Worksheet As Variant
Dim reconcile As Range
For Each cell In Range("d6:d236")
Set ICT_Number = ActiveCell
Set statementdata = Worksheets("m0017 v p0903").Range("H2016")
Set checklistdata = ActiveCell.Offset(0, 5)
Set currsheet = Worksheets("m0017 v p0903")
Set reconcile = ActiveCell.Offset(0, 11)
If InStr(1, cell, ICT_Number, 1) Then
If statmentdata = checklistdata Then
reconclie.Value = "this line reconiles"
Else
reconcile.Value = "this line does not reconclie"
End If
Next cell
End Sub
You have several issues in your code:
Don't use protected (or ambiguous) names for your variables.
Please DON'T DO:
Dim Worksheet As Variant
Better do:
Dim ws as Worksheet
Use Set when assigning an object
This WON'T work:
currsheet = Worksheets("statement n0246 v ab119")
Instead, do:
Set currsheet = Worksheets("statement n0246 v ab119")
What your code could look like
Sub test()
Dim ICT_Number As Range
Dim statmentdata As Range
Dim checklistdata As Range
Dim Worksheet As Variant
Dim reconcile As Range
Set ICT_Number = Worksheets("checklist").Range("D79")
Set statementdata = Worksheets("n0246 v ab119").Range("H2016")
Set checklistdata = Worksheets("checklist").Range("H79")
Set currsheet = Worksheets("statement n0246 v ab119")
Set reconcile = Worksheets("checklist").Range("N79")
If currsheet.Name = ICT_Number Then
If statmentdata = checklistdata Then
reconclie.Value = "this line reconiles"
Else
reconcile.Value = "this line does not reconclie"
End If
End If
End Sub
Before anything else
Please have a look at a VBA Tutorial to learn the syntax: VBA: Basic Syntax and Examples Tutorial