Copying from a specific range in Excel using VB.NET - vb.net

I am currently building a program where I copy a pivot table from one workbook and copy it into another, and am currently having trouble copying the table, as the number of rows depends on how many people buys a product every month. I tried using a UsedRange on that specific range, and it didn't work. Something along these lines...
targetSheet.Range("N3:S50").UsedRange.Copy()
Any ideas?

The following code grabs the data for a particular sheet (in this case tSheet). It then finds the upper-left cell address, copies all data, deletes everything from the spreadsheet, and then pastes it back. This has the effect of resetting the UsedRange on a particular sheet.
Dim values 'holds info on the usedRange of the current spreadsheet
Dim usedRangeAddress As String 'holds the address of the usedRange of the current spreadsheet (i.e. "A1")
usedRangeAddress = tSheet.UsedRange.Address 'get the upper most left cell address
values = tSheet.UsedRange.Value'Store values of all cells to array.
tSheet.Cells.Delete() 'Delete all cells in the sheet
tSheet.Range(usedRangeAddress).Value = values'Restore values to their initial locations
So, with this, you should be able to utilize the first line of code, and then a second line to paste to your otherSheet
Dim values 'holds info on the usedRange of the current spreadsheet
values = tSheet.UsedRange.Value'Store values of all cells to array.
otherSheet.Range(yourTargetAddress).Value = values

Range("A1:B2").Select
Selection.Copy

Related

Naming a dynamic cell range based on another worksheet.

I want to set up a dynamic cell range, which varies length and start point of the range based on user inputs.
I've named a range using the following formula:
=OFFSET(INDIRECT("P"&'FTB data (ML2)'!$N$420),0,0,'FTB data (ML2)'!$N$422,1)
Where:
FTB data (ML2) is the worksheet with the source of data
P is the start column of the data
N420 contains an input for the start row of the range
N422 contains the input for the length of the range
Now this all seems to more or less work, the length varies according to the value in N422 and the start varies based on N420.
The problem is that it's not fixed to the FTB data (ML2) worksheet. I.e when I change tabs to my Summary Sheet, it draws from the range in the summary sheet, no tthe FTB data sheet.
Does anybody have any idea how to make sure it only draws from FTB data, and not the currently active sheet?
Thanks!
I managed to get it working with the following formula:
=OFFSET(INDIRECT("'" & "FTB Data (ML2)" & "'!" & "P"&Summary!$C$1),0,0,'FTB data (ML2)'!$N$422,1)
Turns out you just need a few more ' and " floating about to get an INDIRECT to reference another worksheet correctly.

Transferring information from input sheet to master sheet

I am trying to move data from one workbook 'input worksheet' to another workbook 'master workbook'. Both sheets are in the same file and if possible, it would be great if both files didn't have to be open at the same time in order to transfer the data but the master workbook would autosave once the data was transferred across. Links to images of the files below to make it easier to understand what I am trying to do.
The data in the input worksheet is in row 6, columns A-J with each user inputting details of the tasks they get asked to complete. I would like when a button is clicked, the data from the input worksheet is transferred into row 2, columns B-K in the master workbook so that each time a new task is entered and transferred across, it appears in the row below (so that it can be pivoted later, etc.).
http://i.stack.imgur.com/b2cyI.jpg - input sheet
http://i.stack.imgur.com/JZr0a.jpg - master sheet
Use the macros here to get the last row in the master sheet.
Then simply write the values from the input sheet to the corresponding cell in the master sheet.
That is all. This is how you refer cells:
tbl_master.cells(1,3) = tbl_input.cells(3,5).value
Make sure that the row in the tbl_input is a variable, coming from the function, calculating the last row. Give it a try!
Edit:
This is what I use for last row:
Public Function last_row_with_data(ByVal lng_column_number As Long, shCurrent As Variant) As Long
last_row_with_data = shCurrent.Cells(Rows.Count, lng_column_number).End(xlUp).Row
End Function
If you want to find the last row of column B of sheet "tbl_main" you call it like this:
last_row_with_data(2,tbl_main)
Edit2:
Change the names of your sheets here, and reference them by their names.
In order to get this window, select the sheet on the left and press F4.

Print dynamic Excel page with changing content

I have an Excel workbook with two worksheets.
On the first one I have a "form" and on the second all the data in a table.
What I have done is that on the first sheet I change an ID number, then a function looks at the second sheet to find the ID number and then changes the data on the cells I've specified to those on the second page.
It is for paying company employees and there are currently 50 unique ID's.
Is there a way to print the first sheet with different content in one click if possible? Does anyone know a way to do this?
You can use something like this For each myCell in worksheets(2).range("A1:A50")...next myCell to loop through all the stored cells with different ID's and put each of the value to the cell on the sheet 1.
This is what I mean
Sub PrintAll_IDs()
For Each myCell In Worksheets(2).Range("A1:A50") 'range with stored ID's
Worksheets(1).Range("A1") = myCell.value ' "A1" is the cell with ID that you change manually now
Worksheets(1).PrintOut ' I'm not sure how to print using VBA, just showing the workflow
Next myCell
End Sub

Keeping column formulas in a table header

Is it possible to have the formulas that I need applied on columns be saved or applied to a column header or some kind of metadata so that as and when I add new rows to my Excel table the Formulas get applied to the columns?
Scenarion:
I am creating a template Table, which will have no rows at first.
On a separate sheet (or same sheet for that matter) once the user selects the number of rows to be generated in the table, I dynamically add rows to the table using VBA.
The idea is I may not have any rows in the table at beginning OR user may have deleted rows manually.
When I programmatically add new rows, I want the Formulas applied on the cells as well. Most of the formulas I am using are either of the three types:
Structured table reference, Excel functions like SUM, AVERAGE etc and custom function names.
Updated:
Here is what I have tried:
1> tried applying the formula to the header itself.
Result: The header it self changes with #REF! error. I think the behavior is correct. So it's a no-go option.
2> Tried creating one row and apply the formula to the row. That works, but the problem is, I do not want a dummy row to begin with.
3> Using VBA code to add row to the table using
ActiveWorkbook.Worksheets("Sheet3").ListObjects("Table2").ListRows.Add AlwaysInsert:=True
inside a for loop.
The new rows retain the visual style sheets, but does not seem to retain the formulas. Just blank cells.
Could the fomrmulas be in header cell commnets?
And then with VBA add the formula for the current row:
Sub test()
Dim headerCells As Range
Set headerCells = Range("B2:E2")
OnNewRow 3, headerCells
End Sub
Sub OnNewRow(newRow As Integer, headerCells As Range)
Dim headerCell As Range, targetCell As Range, formulaFromComment As String
For Each headerCell In headerCells
formulaFromComment = GetFormulaFromComment(headerCell)
If (formulaFromComment = "") Then _
GoTo NextHeaderCell
Set targetCell = Intersect(headerCells.Worksheet.Rows(newRow), _
headerCell.EntireColumn)
AddFormula newRow, targetCell, formulaFromComment
NextHeaderCell:
Next
End Sub
Sub AddFormula( _
newRow As Integer, _
targetCell As Range, _
formula As String)
formula = Replace(formula, "{ROW}", newRow)
targetCell.formula = formula
End Sub
Function GetFormulaFromComment(headerCells As Range) As String
' TODO
GetFormulaFromComment = "=SUM($C${ROW}:$E${ROW})"
End Function
Just use tables.
If you highlight cells and choose Insert Table from the ribbon, it doesn't just give you formatting and filters. It also, if you build them the right way, stores column formulas once per column instead of once per cell. Also, the formulas are more readable!
For formulas, you can't use cell addresses if you want it to be a single column formula unless they are absolute. (E.g. $A$1, not A1.) Instead, you use [ColumnTitle] for the entire column (where "ColumnTitle" is the actual title of that column) and [#ColumnTitle] for the column value in the same row. So if "Cost" was the title of column B, "RunningTotal" was the title of column C and your formula for C6 was therefore =B6+C5, you'd instead use a formula of =[#Cost]+OFFSET([#RunningTotal],-1,0)] which is longer but much easier to read/maintain/debug, and if you change a column title then the formulas change too! No VBA required. Given this, plus being able change columns for the entire columns at once, plus being able to refer to other columns in other tables without worrying about cell addresses (e.g. MAX(Table1[Cost])), plus being able to style the tables so easily, plus the integration with Power-Query, and VBA support. (See learn.microsoft.com.) Whether VBA or otherwise, add a row to your table and the columns with a single column formulas will automatically carry over into the new row.
Not sure about Table templates or VBA but perhaps there is another option by using =ARRAYFORMULA()
For example, say you had a header row and 3 columns and wanted your last column to be the product of the first two. In cell C2 you could enter the following:
=ARRAYFORMULA(A2:A*B2:B)
This has three benefits:
Skips the first row completely
Effectively applies the formula to every row which is useful if you later decide to insert a row (your question)
Only one location to modify the formula for every single row
Although, it may not be immediately obvious where how/where the cells are being calculated. (hint: ctrl+~ may help)

How do I increment cell in Excel VBA script?

I have a data in excel which I want to make a VBA script to copy it into a new worksheet but in a different way.
For example, I have this in sheet1 in A1~A3 cells.
Adam(A1)
Sam(A2)
Smith(A3)
I want to use these cells and create the following in another worksheet using refedit control.
Adam(A1)
Adam(A2)
Adam(A3)
Adam(A4)
Sam(A5)
Sam(A6)
Sam(A7)
Sam(A8)
Smith(A9)
Smith(A10)
Smith(A11)
Smith(A12)
I have refedit control in place in VBA script, but I'm not sure how to increment cell numbers to make it copy and paste into a new worksheet. I would like to use refedit control so that I can assign any cells and make it copy and repeat itself. How do I do this in VBA script?
Check out the Range Rows, Cells, and Address properties. This should help. Your question is too vague for a direct answer.
(This will get you started.)
Range.Row Property
http://msdn.microsoft.com/en-us/library/bb221550(office.12).aspx
Returns the number of the first row of the first area in the range. Read-only Long.
Example
For Each rw In Worksheets("Sheet1").Rows
If rw.Row Mod 2 = 0 Then
rw.RowHeight = 4
End If
Next rw
To increment cells in Excel VBA, you can use the Offset-property of the Range-object, e.g.
ActiveCell.Offset(1, 1).Select
will select the cell one row down and one column to the right of the active cell.
To add to Geoffrey's answer about active cell - it would also require that you activate the sheet you are looking to input your values if it is a different sheet from the one that is currently active. Additionally you would have to activate a cell to use activecell and the activecell offset property.
For example
'Activates the name of the sheet you would like to activate
Sheets("Sheet2").Activate
'Activates cell A1
Range("A1").Activate
'Activates cell one row down, one column right
ActiveCell.Offset(1,1).Select
'if current sheet is not activate you just do Sheets("Sheet2").Range("A1").Activate
The offset property of ActiveCell refers to other cells based off of the current active cell.
For example-
Offset(row,column) -
First Argument -Positive values as the first argument refer you to rows below the current active cell and Negative values refer you to rows above the current active cell
Second Argument-Positive values as the second argument refer you to columns right of the current active cell and Negative values refer you to columns left the current active cell