» Copy Selection to a Database sheet using VBA in Microsoft Excel
VBA macro tip contributed by Ron de Bruin, Microsoft MVP - Excel
CATEGORY - Cells, Ranges, Rows, and Columns in VBA
VERSION - All Microsoft Excel Versions
- The example codes will copy to a database sheet with the name Sheet2.
- Every time you run one of the subs the cells will be placed below the last row with data or after the last Column with data in sheet2.
- For each example there is a macro that does a normal copy and one that is only Copy the Values.
- The Example subs use the functions below (the macros won’t work without the functions).
Sub CopySelection()
Dim destrange As Range
If Selection.Areas.Count > 1 Then Exit Sub
Set destrange = Sheets("Sheet2").Range("A" & _
LastRow(Sheets("Sheet2")) + 1)
Selection.Copy destrange
End Sub
Sub CopySelectionValues()
Dim destrange As Range
Dim Lr As Long
If Selection.Areas.Count > 1 Then Exit Sub
Lr = LastRow(Sheets("Sheet2")) + 1
With Selection
Set destrange = Sheets("Sheet2").Range("A" _
& Lr).Resize(.Rows.Count, .Columns.Count)
End With
destrange.Value = Selection.Value
End Sub
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
Function Lastcol(sh As Worksheet)
On Error Resume Next
Lastcol = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
End Function
Book Store:
Recommended Books:
- Investing in Real Estate, Fourth Edition
- Rich Dad, Poor Dad: What the Rich Teach Their Kids About Money--That the Poor and Middle Class Do Not!
- Absolute Beginner's Guide to Microsoft Office Excel 2003
- Special Edition Using Microsoft Excel 2002
- Microsoft Excel Version 2002 Step by Step
- Your First Business Plan: A Simple Question and Answer Format Designed to Help You Write Your Own Plan (3rd Ed)
No comments have been submitted.

