Create a range using named cells - vba

I need to create a range using named cells in vba.
So far I have the following which is not working;
Dim pasteRange As Range
Set pasteRange = Range(firstRow, 11)
pasteRange.Value(11) = slabTemplateSheet.Range("slabTemp").Value(11)
Where firstRow is an Integer. slabTemplateSheet refers to a worksheet and slabTemp is a named range in said sheet.
I thought it would be fairly simple as my paste range is only 1 row and 11 columns (i.e 11 cells in a row) but I can't get it to work.
In your answer, presuming there is one, could you also please give me the ability to paste multiple rows and columns, so for instance if slabTemp refers to A1:F16
Edit: I didn't make it clear what I am trying to do.
I have a named range called slabTemp in the worksheet slabTemplateSheet. In another sheet I want to copy that range, including the formatting, and paste it. I heard that using the copy/paste function was slow so I found the property above that supposedly does the same thing but is faster (i haven't tested it). Source, Durgesh's answer here: fast way to copy formatting in excel
In the new sheet I need to paste it into a range which is to be created (this is what i don't know how to do)
So Range(firstRow, 11) refers to the integer saved as firstRow (a row number) and 11 is the column number. But this doesn't work.
I guess my question, is how do i create a range using names rather than say Range("A1:G6") so instead Range(firstRow1:secondRow:6)
Thanks Again!

Here's a working example.
Public Sub CopyRange()
'Define the Copy Range
Dim CopyRange As Range: Set CopyRange = Range("MyCustomRange")
'Define the range to Paste Value to
Dim PasteRange As Range: Set PasteRange = Range("MyOtherCustomRange")
'Move the Copy Range into the Paste Range
'You don't need to specify the sheet name, the Defined named holds that information
'Important: The ranges should be the same size, otherwise you may get an error
PasteRange.Value() = CopyRange.Value()
End Sub

About how to create a Named Range (worksheet scope, not for Workbook per your code), use the code below. Not sure what are you trying to achieve in this line:
pasteRange.Value(11) = slabTemplateSheet.Range("slabTemp").Value(11)
Anyway, this is the code for the Named Range:
Sub UseNamedRange()
Dim slabTemplateSheet As Worksheet
Dim pasteRange As Range
Set slabTemplateSheet = Sheets("Sheet1")
' create the Named Range "slabTemp" (Named Range for Worksheet)
' you can manualy (or with variables) modify the Range("A1:F16")
slabTemplateSheet.Names.Add "slabTemp", Sheets("Sheet1").Range("A1:F16")
Set pasteRange = slabTemplateSheet.Range("slabTemp")
End Sub

It doesn't seem like you are trying to transfer the xlRangeValueXMLSpreadsheet XlRangeValueDataType enumeration of the cells; rather it sounds like you want 11 cells in a row.
with slabTemplateSheet.Range("slabTemp")
pasteRange.Resize(1, 11) = .Cells.Resize(1, 11).Value
end with

Related

Copy a static range on one sheet, and paste in a dynamic range in another sheet based on a single value in a cell

I have three parts to this problem. I have a single cell with a Week number in Sheet1!A1. I have a static range in Sheet1!B1:F1 that needs to be copied. Then I need to paste the value in a dynamic range in Sheet2 offset by the week number for rows. This is part of a larger macro I am writing for a sheet I use regularly, but I seem to have those parts down. I may be either oversimplifying or oversimplifying but this is what I have currently.
Sub CopyPaste()
Sheets(1).Range("B1:F1").Copy
OffsetRange = Sheets(1).Cells(1,1).Value
Sheets(2).Cells(1+OffsetRange,1).Paste
End Sub
When I run this, it either gives me a Runtime Error 9 or Runtime Error 438.
Anyone know whats causing these errors? When I paste the range, does the cells object point towards the first cell of the copied range when I paste in at the location?
Try it as,
Option Explicit
Sub CopyPasteOffset()
Dim OffsetRange As Long
OffsetRange = Worksheets(1).Cells(1, 1).Value
Worksheets(1).Range("B1:F1").Copy _
Destination:=Worksheets(2).Cells(1 + OffsetRange, 1)
End Sub
The .Paste method is a member of Worksheet, not Range or Cells. You may have it confused with .PasteSpecial which is a member of the Range object. In any event, it is unnecessary as a destination can be applied directly to the copy command.

How to use range object with a worksheet object

I am writing a simple program to merge cells in different sheet.
I wrote this code
Dim ws as worksheet
Set worksheet = sheets ("sheets2")
ws.range (cells (1,1),cells (1,5)).merge
This is not working and error comes saying method range of object worksheet failed
Please help me with this
Thank you
Try like this:
Option Explicit
Sub TestMe()
Dim ws As Worksheet
Set ws = Sheets("sheets2")
With ws
.Range(.Cells(1, 1), .Cells(1, 5)).Merge
End With
End Sub
The range object is a bit difficult in Excel and when you are referencing to cells you should also reference to the sheet.
Take a look at the Microsoft examples, they are good:
https://msdn.microsoft.com/en-us/library/office/ff838238.aspx
Especially the third note:
Be aware that the period in front of each occurrence of the Cells property. The period is required if the result of the preceding With statement is to be applied to the Cells property—in this case, to indicate that the cells are on worksheet one (without the period, the Cells property would return cells on the active sheet).

Excel 2013: Use macro to copy and subsequently add data from one sheet to another within same workbook

I have used the various methods pointed out in this forum and none seem to work, so I will try to be more specific.
I have a workbook called LIBRARY.xlsm.
This workbook contains two worksheets: CALCULATOR and CUTS.
The worksheet CALCULATOR contains two tables: INPUT and OUTPUT.
I enter data into INPUT, values are calculated and automatically entered into OUTPUT.
I create a button below OUTPUT with macro to copy data in OUTPUT to worksheet CUTS.
I enter new data into INPUT, which then updates OUTPUT.
Now I want to copy this new data to CUTS without overwriting or deleting previous data.
Since this project is divided into 5 sections, I should end up with five tables in the worksheet CUTS that I can then print out.
The INPUT table encompasses cells A1:M31, which does not matter (I’m not copying this).
The OUTPUT table occupies cells O6:S26. This is the data that needs to be copied.
Placement into worksheet CUTS can start at cell A1 (which means the table will have the range A1:E20). I would like to skip a column and then place the next data set. Thus, the next data set should begin at G1 (G1:K20), then at M1:Q20 and so forth). Maybe only go three tables across and then start next three below (separated by row).
Here is the code tried to use. Problem is, it does not retain the values and it overwrites the previous data.
Sub Create_CUTS ()
Dim sourceSheet As Worksheet
Dim sourceRange As Range
Dim sourceRows As Integer
Set sourceSheet = Worksheets("CALCULATOR")
sourceRows = WorksheetFunction.CountA(sourceSheet.Range("A:A"))
Set sourceRange = sourceSheet.Range("O6:S26" & sourceRows)
Dim targetSheet As Worksheet
Dim targetRange As Range
Dim targetRows As Integer
Set targetSheet = Worksheets("CUTS")
targetRows = WorksheetFunction.CountA(targetSheet.Range("A:A"))
Set targetRange = targetSheet.Range("A" & targetRows + 1 & ":A" & targetRows + 1 + sourceRows)
sourceRange.Copy Destination:=targetRange
End Sub
Thank you, everyone
-Grumps
There are a few ways to do this. The easiest is probably to just reference the usedrange of the target sheet to know where you left off with the last paste.
lastUsedRow = targetSheet.UsedRange.Rows.Count
lastColumnUsed = targetSheet.UsedRange.Columns.Count
Then you just add a column or row and paste the table in the new location. If the column count is 22 or greater, add a row and paste at "A" and the lastUsedRow + 2. There is some potential for this to be wrong if the sheets are saved with cells that are empty, but excel reads them as "used" (somehow people I work with manage to do this all the time, I don't even know how they do it). It sounds like this is something that users won't be manipulating, so I wouldn't think that would be a problem, but if it is a possible problem for you, you can use a loop to find the next empty cell instead of using the built in "usedrange" collection.

Referencing multi-sheet named range in VBA

I have a named range in Excel that I am trying to clear using VBA.
The problem with the range is that spans across multiple sheets and I am not sure how to properly reference the named range in VBA since it covers multiple sheets.
The Named Range "Counts" is set to Workbook scope with the following cell references:
=Sheet1!$A$1, Sheet2!$A$1, Sheet3!$A$1
When clearing a named range where it only has cells referenced on one sheet I use the following:
ThisWorkbook.Sheets("Sheet1").Range("Counts").ClearContents
I have tried the following but neither seemed to work.
ThisWorkbook.Range("Counts").ClearContents
and
Range("Counts").ClearContents
The last gives me a global error.
Instead of a range that goes across multiple sheets (which does not work, as we have established), you need a worksheet scoped range in each sheet.
When defining a range name you can set its scope to workbook or the current sheet. This way you can have the same range name in many sheets.
Use VBA to loop through all worksheet, access the ws.Range("TheRangeName") on the current sheet and clear its contents.
That's a cleaner approach.
I would write something that displays the names and you can use that to remove it...
In the immediate window:
For i = 1 to names.count:Debug.print i, Names(i).RefersTo, Names(i).name:next
You can then either use th name or the index to remove the particular name you want.
Hope that helps.
Rory Archibald states on his website post about named ranges that: A Range object can only refer to cells on one worksheet. You cannot refer to cells on different sheets with one Range object.
So I am unable to accomplish what I was wanting but I should be able to just create multiple named ranges and just clear them one at a time.
I was able to complete the code for this as follows with inspiration from teylyn
Public Sub ClearRanges()
'Checks if named Range exists on sheet if it does then clear contents
Dim ws As Worksheet
Application.DisplayAlerts = False
For Each ws In ThisWorkbook.Worksheets
If Len(ws.Range("Counts").Name) <> 0 Then
ws.Range("Counts").ClearContents
End If
Next ws
Application.DisplayAlerts = True
End Sub

copying different ranges of cells in excel according to styling

Im using a pivot table to arrange my data. when I copy my data to another sheet its looks like that:
but I want the data to be one by the other like that:
how can I use the bold lines as headers and cut only the required ranges which are not fixed? I tried using macros but I could only copy fixed ranges so I'm doing it manually each time (and some om the sheets are pretty big).
please help,
thank you.
You have full control on all the cells in the PivotTable. Sample code:
Dim curpivottable As PivotTable
Set curpivottable = ActiveSheet.PivotTables(1)
Dim curRange As Range
Set curRange = curpivottable.TableRange1
For Each cell In curRange.Cells
If (cell.Font.Bold) Then
'This is a bold cell
End If
Next cell
Bear in mind that curRange includes all the contents in curpivottable, from the first row (where the title is).
-- UPDATE
My answer above was the generic way to deal with ranges in PivotTables. If all what you want is just copying/pasting a range, you can do it directly (is the same if the range is in the PivotTable or not). Example:
Dim origRange As Range
Set origRange = Sheets("Sheet1").Range("A2:A500")
Dim destRange As Range
Set destRange = Sheets("Sheet2").Range("A2")
origRange.Copy
destRange.PasteSpecial xlPasteValues
Equivalently, you can check the format of the given cells (being bold or not) independently upon being inside a PivotTable or not.