Copy selected cells from one workbook and copy to another - vba

I am trying to create a database which will copy a selected range of data from a main workbook and copy into a separate workbook.
The code causing the issue is below. The 2nd workbook opens based on the value of "W2". A new row should be inserted to the new Wb and formatted then the value of the selected cells pasted.
'Select data to be copied
ActiveCell.Resize(1, 4).Copy
'Open Lessons Learned Db
Location = Range("W2").Value
Set Lessons = Workbooks.Open(Location)
Set LL = Sheets("Lessons Learned")
Windows("Lessons Learned Database.XLSM").Activate
Sheets("Lessons Learned").Activate
'Insert New Row
Range("5:5").Activate
ActiveCell.Offset(1).EntireRow.Insert
'Enter Odd Or Even VALUE
Range("A7").Select
OE = ActiveCell.Value
If OE = 1 Then
Range("A6").Select
ActiveCell.FormulaR1C1 = 0
Else
Range("A6").Select
ActiveCell.FormulaR1C1 = 1
End If
'Hide Permanently Hidden Rows -LINE BELOW GIVES ERROR 1004
Rows("5:5").Select
Selection.EntireRow.Hidden = True
Columns("A").Select
Selection.EntireColumn.Hidden = True
'FORMAT ROW
Range("A6").Select
SC = ActiveCell.Value
If SC = 1 Then
Range("B6:N6").Select
With Selection.Interior
.ColorIndex = 15
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With
End If
Range("B5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Any pointer on where I'm going wrong would be greatly appreciated.

Its advised not to use .Select or .Activate as there are other ways to accomplish this.
Because you were selecting and activating this could have caused the ERROR 1004.
Below i have "cleaned up" your code defining Lessons, LL and Location and included MainWB and defined your ranges.
By defining your Range Excel will always get the .Value from that Range there is then no need to use .Select or .Activate.
As far as tested the below code works:
Sub CopyMainWBtoNewWB()
Dim Lessons As Workbook
Dim LL As Worksheet
Dim MainWB As Workbook
Dim Location As String
Set MainWB = Workbooks("Name Here")
'Open Lessons Learned Db
Location = MainWB.Sheets("Sheet Name").Range("W2").Value
Set Lessons = Workbooks.Open(Location)
Set LL = Lessons.Sheets("Lessons Learned")
'Insert New Row
LL.Rows(5).Offset(1).EntireRow.Insert shift:=xlDown
'Enter Odd Or Even VALUE
If LL.Range("A7").Value = 1 Then
LL.Range("A6").Value = 0
Else
LL.Range("A6").Value = 1
End If
'Hide Permanently Hidden Rows -LINE BELOW GIVES ERROR 1004
LL.Rows(5).Hidden = True
LL.Columns(1).Hidden = True
'FORMAT ROW
If LL.Range("A6").Value = 1 Then
With LL.Range("B6:N6").Interior
.ColorIndex = 15
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With
End If
MainWB.Sheets("Sheet1").Range("A1:A4").Copy
LL.Range("B5").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End Sub
All you need to do is change the Workbook name of MainWB and the Sheet name its collecting the Valuefor Location.

I suspect your code has some other issues that Code Review may be able to help with but to answer your question:
The Rows("5:5").Select is being passed the wrong argument data type.
Worksheet.Rows() is expecting a number, either Integer or Long data type but you are giving it a string.
Change it to Rows(5) and it should work.

That can all be consolidated to:
ActiveCell.Resize(1, 4).Copy '// not sure what this is for
Set Lessons = Workbooks.Open([w2])
Set LL = Lessons.Sheets("Lessons Learned")
With LL
.Rows(6).EntireRow.Insert
.Range("A6").value = IIf(.Range("A7").value = 1, 0, 1)
.Rows(5).Hidden = True
.Columns("A").Hidden = True
If .Range("A6").value = 1 Then
With .Range("B6:N6").Interior
.ColorIndex = 15
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
End With
End If
.Range("B5").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End With
You will notice that this code refers directly to each object without activating or selecting it. Coding in this way means that every object is fully qualified and you know exactly which instance you are working with.
This should ensure that the row is correctly hidden without error because you are referring to the Rows collection which is a collection of Ranges with defined properties and methods. Selection can be a sheet, workbook, chart, range or pretty much anything else you can point and click at - so this can cause problems when trying to access properties or methods that belong to a particular object or class.

Related

Excel VBA Dynamic Code Repeat Failure

This code is a bit complex but the problem with it is the second and third time it is run it will start to lose columns on the "Base434" worksheet that it pulls information from. I tried a quick fix of adding "Range("A1").Select so that anything previously highlighted couldn't throw it off but it keeps ditching the 20th row which is column "T". I have left all of the code below in hope that someone can find my bug. I just cannot sort it.
Essentially this code sorts set fields of data on an imported worksheet called "Base434", copies specific fields to another page which has some embeded formulas then checks to see if the worksheet "NoStdHC" exists. If it doesn't it will create said worksheet and add the header. Then move to the filtered worksheet called "Base434" and copy all visible cells in that worksheet. It will then paste those in the first available cell in column A of "NoStdHC". My issue is after running this once it refuses to copy the final column on the next "Base434" sheet that has been imported. Can anyone find the fault in my code? Yes I know a lot of this could be condensed if I were better at coding but I would prefer to understand what the code is doing which is why I have it written this way.
Sub NoStdHC()
'
' NoStdHC Macro created by
'
'
Application.ScreenUpdating = False
Sheets("Base434").Select
LastRow = Cells(Rows.Count, "B").End(xlUp).Row
ActiveSheet.Range("A1:T" & LastRow).AutoFilter Field:=15
ActiveSheet.Range("A1:T" & LastRow).AutoFilter Field:=10
ActiveSheet.Range("A1:T" & LastRow).AutoFilter Field:=10, Criteria1:="<=.5", _
Operator:=xlAnd
Columns(11).Cells.SpecialCells(xlCellTypeVisible).Cells(2).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Processing").Select
Range("AC1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("C5").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=COUNTA(C[26])"
Range("e5").Select
ActiveCell.FormulaR1C1 = "=SUM(C[24])"
Range("C8").Select
Sheets("Base434").Select
Dim wsTest As Worksheet
Const strSheetName As String = "PR0OnStd"
Set wsTest = Nothing
On Error Resume Next
Set wsTest = ActiveWorkbook.Worksheets(strSheetName)
On Error GoTo 0
If wsTest Is Nothing Then
Worksheets.Add.Name = strSheetName
Sheets("Base434").Select
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Sheets("PR0OnStd").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.Columns.AutoFit
Range("A2").Select
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
ActiveWindow.FreezePanes = True
End If
Sheets("Base434").Select
Range("a1").Select
Columns(1).Cells.SpecialCells(xlCellTypeVisible).Cells(2).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Sheets("PR0OnStd").Select
LastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Range("A" & LastRow).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.ScreenUpdating = True
End Sub'
As commented by #A.S.H avoid using Select/Activate/ActiveCell if at all possible. Ranges should be qualified by using their sheet names. With...End With constructs achieve both of these goals. The With statement allows you to perform a series of statements on a specified object without requalifying the name of the object.
Indentation makes code much easier to read and understand.
With the foregoing in mind I think this code is understandable
Sub NoStdHC()
Dim LastRow As Long
Dim sht As Worksheet
Application.ScreenUpdating = False
With Sheets("Base434")
LastRow = .Cells(Rows.Count, "B").End(xlUp).Row
.Range("A1:T" & LastRow).AutoFilter Field:=10, Criteria1:="<=.5"
.Range(.Cells(2, 11), .Cells(LastRow, 11)).Copy
End With
With Sheets("Processing")
.Range("AC1").PasteSpecial xlPasteValues
Application.CutCopyMode = False
.Range("C5").FormulaR1C1 = "=COUNTA(C[26])"
.Range("E5").FormulaR1C1 = "=SUM(C[24])"
End With
Dim wsTest As Worksheet
Const strSheetName As String = "PR0OnStd"
'Loop through sheets to find strSheetName
'if not found, then wsTest will be Nothing
For Each sht In ThisWorkbook.Sheets
If sht.Name = strSheetName Then
Set wsTest = ActiveWorkbook.Worksheets(strSheetName)
Exit For
End If
Next
If wsTest Is Nothing Then
'Add the sheet, set up headings, column widths and frozen pane
Worksheets.Add.Name = strSheetName
With Sheets("Base434")
.Range("A1", .Range("A1").End(xlToRight)).Copy
End With
With Sheets("PR0OnStd")
.Range("A1").PasteSpecial xlPasteValues
.UsedRange.Columns.AutoFit
End With
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
.FreezePanes = True
End With
End If
With Sheets("Base434")
.Range(.Cells(2, 1), .Cells(LastRow, 2).End(xlToRight)).Copy
End With
With Sheets("PR0OnStd")
LastRow = .Cells(Rows.Count, "A").End(xlUp).Row + 1
.Range("A" & LastRow).PasteSpecial xlPasteValues
Application.CutCopyMode = False
End With
Application.ScreenUpdating = True
End Sub
If you wanted to write write code you can easily understand you wouldn't write code like this:-
Sheets("Base434").Select
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
This is what your code says, translated into plain language:-
Look at sheet "Base434"
Look at cell A1 (implied: in that sheet)
Look at what you are looking at and extend your view to the last ??? right
(This is where the mistake is)
Copy what you are looking at.
Now, surely, if you wanted to understand what all this looking is aiming to do you might express the idea somewhat like this:-
Copy the cells in Row 1 of Sheet "Base434" from A1 to the end of the row.
With this kind of approach you would end up with code like this:-
Dim RangeToCopy As Range
Dim Cl As Long ' the last used column
With Worksheets("Base434")
Cl = .Cells(1, .Columns.Count).End(xlToLeft).Column
Set RangeToCopy = .Range(.Cells(1, 1), .Cells(1, Cl))
End With
MsgBox "Range to copy = " & RangeToCopy.Address
RangeToCopy.Copy
Would you say that this code is harder to read and understand than your version? Well, it has three advantages, even if it is. One, it doesn't have the fault that yours has. Two, it never got near to wanting to make the mistake that your approach made. Three, whatever errors it might still contain are easy to find and quick to eliminate.
Besides, it runs faster.

VBA Macro: Formula is Based on a Column that changes locations

i'm trying to tweak my macro so that it creates a column next to a specific column that always changes positions. In the macro i have below, it is just an absolute reference of 6 columns to the left. However, this wont always be the case. Should I set this up by finding the column name in the top row?
Basically the macro creates a new column and puts in an IF statement if it is a duplicate, and then sets up conditional formatting to highlight all the values of "1". Sorry if i am not explaining this clearly!
Sub test()
Columns("L:L").Select
Selection.Insert Shift:=xlToRight
Range("L2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-6]=R[-1]C[-6],R[-1]C+1,1)"
Range("L2").Select
Selection.Copy
Range("K2").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Calculate
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=1"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.Color = -16383844
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13551615
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub
I have a working code for this but it requires that your data be in a table. This is the best way to dynamically manipulate and reference the data (Columns, Rows, etc..)
Also I heavily rely on the ListObject method. It really handles tables well.
Public Sub InsertColumn(Optional columnName As String, Optional BeforeORAfter As String)
Dim loTableName As ListObject
Dim loColumn As ListColumn
Dim newColDest As Long
'Handles user input if they desire the column inserted before or after
Select Case UCase(BeforeORAfter)
Case Is = "BEFORE"
newColDest = 0 'Inserts column and moves reference column right
Case Else
newColDest = 1 'Inserts column to the right of reference column
End Select
'Ensures the user selects a reference column name
Select Case columnName
Case Is = ""
columnName = InputBox("Enter column name to be referenced.", "Enter Column Name")
Case Else
End Select
'Sets the ListObject as the table.
Set loTableName = Range("TableName").ListObject
With loTableName
On Error GoTo InsertError 'Exits sub in case the column couldn't be found
.ListColumns.Add (.ListColumns(columnName).Index + newColDest)
End With
Exit Sub
InsertError:
'Most likely error is user typed the column header incorrectly.
MsgBox "Error creating column. Ensure a correct reference column was chosen", vbExclamation + vbOKOnly, "Insert Error"
End Sub
Any questions or problems, just let me know.
This below would be something you can work with (it will ask the column to search and perform the actions in your recorded macro...
Check my website http://multiskillz.tekcities.com/k2500_0vbaMenu.html
Sub test_modified()
'worksheet workbook object
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(1)
'range object to select a column
Dim fRng As Variant
fRng = Application.InputBox(Prompt:="value to find", Title:="InputBox Method", Type:=2)
'range object to find the column
Dim colRng As Range
Set colRng = ws.Rows(1)
'find column
Dim fcol As Range
Set fcol = colRng.Find(fRng, LookIn:=xlValues, lookat:=xlPart, MatchCase:=False)
'convert the column address to a number
Dim colNb As Byte
colNb = fcol.Column
'going on from your recorded macro
'Columns("L:L").Select
ws.Columns(colNb).Select
Selection.Insert Shift:=xlToRight
Range("L2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-6]=R[-1]C[-6],R[-1]C+1,1)"
Range("L2").Select
Selection.Copy
Range("K2").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Calculate
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=1"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.Color = -16383844
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13551615
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub
Cheers
Pascal

how do I copy same columns which are laterally placed from different worksheets into a single worksheet?

I have 50 worksheets in a workbook. columns a,b,c,d are same as columns e,f,g,h, but both sets might have different number of rows/observations. I need to consolidate all in a single sheet having only 3 columns. I need to append the column names, start copying and pasting (values) from 3rd row onwards (till end of data). I tried recording a macro too but in that case, I have to go through all the sheets manually. Can someone lead me to the right direction? I'm very new to VBA and a little help will be much appreciated. My recorded macro for copying 2 sheets goes like this:
Sheets("page 9").Select
Range("A3:D3").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ActiveWindow.ScrollWorkbookTabs Position:=xlLast
Sheets.Add After:=Sheets(Sheets.Count)
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.End(xlDown).Select
Range("A67").Select
ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
Sheets("page 9").Select
Range("E3:H3").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
ActiveWindow.ScrollWorkbookTabs Position:=xlLast
Sheets("Sheet1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.End(xlDown).Select
Range("A132").Select
ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
Sheets("page 10").Select
Range("A65").Select
Selection.End(xlUp).Select
Range("A3:D3").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
ActiveWindow.ScrollWorkbookTabs Position:=xlLast
Sheets("Sheet1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.End(xlDown).Select
Range("A197").Select
ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
Sheets("page 10").Select
Range("E3:H3").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
ActiveWindow.ScrollWorkbookTabs Position:=xlLast
Sheets("Sheet1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.End(xlUp).Select
Range("A1").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "Date"
Range("B1").Select
ActiveCell.FormulaR1C1 = "Type"
Range("C1").Select
ActiveCell.FormulaR1C1 = "Size"
Range("D1").Select
ActiveCell.FormulaR1C1 = "Discount"
Range("A1").Select
End Sub
I doubt that anyone can decypher this code; certainly I lack the ability.
The Macro recorder is a great way of learning the syntax of new commands but it does not produce "good" code. It does not know your objective and records every little step as you do it.
Take the time to study Excel VBA. Search the internet for "Excel VBA Tutorial" or visit a good library or bookshop and select an Excel VBA Primer. There are many to chose from so I am sure you will find something that suits your learning style. This study will quickly repay your investment.
Look through the excel-vba questions on StackOverflow. Many, perhaps most, will be of no current interest to you. But some will show techniques you did not know about but which will be useful. Perhaps the most difficult aspect of learning VBA is discovering what is possible. Once you know statement X exists, you can look it up and study its syntax and functionality.
Below are four macros that demonstrate relevant code. Copy them to a workbook and try them. You could not have learnt how to write these macros from a study of macro recorder output.
A This macro outputs the name of every worksheet to the Immediate Window.
Sub A()
Dim InxWsht As Long
For InxWsht = 1 To Worksheets.Count
Debug.Print Worksheets(InxWsht).Name
Next
End Sub
B This adds a new worksheet at the end of the current list and names it "Consolidate". It then creates a bold, coloured header line.
Range(CellId).Value is one way of accessing a cell's value. I have used "A1" as the cells's Id but this is just a string and could have been built at runtime. Cells(RowId, ColId).Value is another way. RowId must be a number or an integer variable. ColId can be a number, an integer variable or a column letter. I suggest you be consistent and not mix and match as I have.
I show two method of specifying a range so I can set the entire header row bold and coloured in single statements.
If I have written Range("A1").Value = "Date" this statement would have operated on cell A1 of the active worksheet. The . before Range means this statement operates of cell A1 of the worksheet identified in the With statement. Using With means I do not have to switch worksheets using Select which is a slow command.
Sub B()
Dim WhshtCons As Worksheet
Set WhshtCons = Sheets.Add(After:=Sheets(Sheets.Count))
WhshtCons.Name = "Consolidate"
With WhshtCons
.Range("A1").Value = "Date"
.Cells(1, 2).Value = "Type"
.Cells(1, "C").Value = "Size"
.Cells(1, 4).Value = "Discount"
.Range("A1:D1").Font.Bold = True
.Range(.Cells(1, 1), .Cells(1, "D")).Font.Color = RGB(0, 128, 128)
End With
End Sub
C This outputs the value of Cell A1 of every worksheet except "Consolidate".
Sub C()
Dim InxWsht As Long
For InxWsht = 1 To Worksheets.Count
If Worksheets(InxWsht).Name <> "Consolidate" Then
With Worksheets(InxWsht)
Debug.Print "Cell A1 of Worksheet " & .Name & " contains [" & _
.Cells(1, 1).Value & "]"
End With
End If
Next
End Sub
D I will not explain this macro because it is somewhat more advanced than the others. It demonstrates moving columns of data from all the other worksheets to worksheet "Consolidate". I doubt this is close to what you seek but it demonstrates that what you seek is possible.
Sub D()
Dim ColConsCrnt As Long
Dim InxWsht As Long
Dim RowLast As Long
Dim WhshtCons As Worksheet
ColConsCrnt = 1
Set WhshtCons = Worksheets("Consolidate")
WhshtCons.Cells.EntireRow.Delete
For InxWsht = 1 To Worksheets.Count
If Worksheets(InxWsht).Name <> "Consolidate" Then
With Worksheets(InxWsht)
RowLast = .Cells(Rows.Count, "A").End(xlUp).Row
WhshtCons.Cells(1, ColConsCrnt).Value = .Name
.Range(.Cells(1, "A"), .Cells(RowLast, "A")).Copy _
Destination:=WhshtCons.Cells(2, ColConsCrnt)
End With
ColConsCrnt = ColConsCrnt + 1
End If
Next
End Sub
Welcome to programming. I hope you find it as much fun as I do.

Copying the Merge-Formatting of a Table Using VBA

I'm trying to create a macro that works on columns that are adjacent to an existing table. The purpose of this macro is to take any cell merges that exist in the table and copy them into the next two columns (It's a helper method for something with a larger purpose). My code is below but I'm getting an error that says, "PasteSpecial method of Range class failed" which occurs on the line:
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
The line directly above was a test line to check if the code was working for the first iteration of the loop, which it is. Once the code tried to re-iterate and paste again, however, the code fails. I believe it's because the 'Selection.PasteSpecial' call is not referencing the correct object anymore but I'm not sure how to fix it.
Sub extendColumnMerges()
'
' Works on a column adjacent to a table by extending the column's merge-formatting to the selected column
' Active cell must begin as the first cell in the column immediatley adjacent the table on the right
'
Dim cols As Integer
cols = 2
'Selects the last column of the table and copies the selection into the new column, modifying the format of the new column
Range(ActiveCell.Offset(0, -1), ActiveCell.Offset(0, -1).End(xlDown)).Select
Selection.Copy
'Pastes the columns' merge-formatting into each specified column adjacent the table on the right
For c = 1 To cols
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveCell.Value = "Yes"
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
'Removes the formatting from the cells in the new column
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
'Removes borders from the newly modified column
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Selection.Borders(xlEdgeLeft).LineStyle = xlNone
Selection.Borders(xlEdgeTop).LineStyle = xlNone
Selection.Borders(xlEdgeBottom).LineStyle = xlNone
Selection.Borders(xlEdgeRight).LineStyle = xlNone
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
ActiveCell.Select
Next c
End Sub
Also, if there are any suggestions as to how to code this in a more elegant manner they would be greatly appreciated. Copying the formatting and then removing the borders and fills seems bulky in code. Thanks.
This seemed to work for me:
Sub Tester()
'copy the merged areas of the current selection 4 columns to the right
ReplicateMergeAreas Selection, 4
End Sub
Sub ReplicateMergeAreas(sourceArea As Range, colOffset As Long)
Dim rw As Long, col As Long
Dim c As Range, c2 As Range
Dim rngTL As Range
'set the cell at the top-left of the "destination" range
' (actually offset -1,-1 to make it easier to set range 'c2')
Set rngTL = sourceArea.Cells(1).Offset(-1, colOffset - 1)
'loop through each cell in the "source" range
For rw = 1 To sourceArea.Rows.Count
For col = 1 To sourceArea.Columns.Count
'c=cell in source range
Set c = sourceArea.Cells(rw, col)
'is this cell merged?
If c.MergeArea.Cells.Count > 1 Then
'c2=corresponding cell in the destination range
Set c2 = rngTL.Offset(rw, col)
'Is the "destination" cell already merged?
' skip if yes
If c2.MergeArea.Cells.Count = 1 Then
'set merge area the same size as the "source" cell
c2.Resize(c.MergeArea.Rows.Count, _
c.MergeArea.Columns.Count).Merge
End If
End If
Next col
Next rw
End Sub
The range passed to the sub must be a single-area rectangular range which completely encloses all the merged areas (or at least their top-left corners) you want to replicate across. colOffset is how many columns over you want to copy the merging to.

paste special in vba

i am trying to use pastespecial in vba..i basically need to paste the values (and not the formulas as the formula gets recalculated while pasting to the new sheet because of change in the cell values in that sheet) to another sheet...But i am getting error 1004 saying 'aaplication defined or object defined error'..heres the code...please help somebdy...
Sub Macro1try()
Dim i As Integer
Dim j As Integer
For i = 1 To 2
Worksheets("Volatility").Cells(1, "B").Value = Worksheets("Volatility").Cells(i, "S").Value
Call mdlMain.ExtractData
Range("A11:D2330").Select
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
ActiveWorkbook.Sheets("Volatility").Activate
Next i
End Sub
This I learned the hard way: Avoid Copy/Paste if at all possible! Copy and Paste use the clipboard. Other programs may read from / write to the clipboard while your code is running, which will cause wild, unpredictable results at both ends.
In your particular case, Copy and Paste are completely unnecessary. Just use =.
For i = 1 To 2
'// Your stuff, which I won't touch:
Worksheets("Volatility").Cells(1, "B").Value _
= Worksheets("Volatility").Cells(i, "S").Value
Call mdlMain.ExtractData
Sheets.Add After:=Sheets(Sheets.Count)
'// The following single statement replaces everything else:
Sheets(Sheets.Count).Range("A11:D2330").Value _
= Sheets("Volatility").Range("A11:D2330").Value
'// VoilĂ . No copy, no paste, no trouble.
'// If you need the number format as well, then:
Sheets(Sheets.Count).Range("A11:D2330").NumberFormat_
= Sheets("Volatility").Range("A11:D2330").NumberFormat
Next i
You need to state where you're putting it on the sheet
Sub Macro1try()
Dim i As Integer
Dim j As Integer
For i = 1 To 2
Worksheets("Volatility").Cells(1, "B").Value = Worksheets("Volatility").Cells(i, "S").Value
Call mdlMain.ExtractData
Sheets.Add After:=Sheets(Sheets.Count)
Worksheets("Volatility").Range("A11:D2330").Copy
Sheets(Sheets.Count).Range("A11:D2330").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Next i
End Sub
Add
".Range("A1")."
Between 'ActiveSheet' and 'PasteSpecial'
Change A1 to the location you want to paste to.