VBA: Naming a table of data using a Macro - vba

I'd like to use a Macro to name a table of data so that I can use that name to create a Pivot Table later in my Macro. The number of rows will change every time I use this Macro,so I need to find one that can identify the last row and grab all the data in Columns A,B,C and D from row 4 down to the last row of data. My code is presented below, I'm getting an error message on the last line. Any help would be much appreciated.
Sub Macro22()
Dim Lastrow As Long
Sheets("Statement").Select
Lastrow = Cells(Rows.Count, "A").End(xlUp).Row
ActiveWorkbook.Names.Add Name:="VendorData", RefersToR1C1:= _
"=Statement!A5:C" & Lastrow
ActiveWorkbook.Names("VendorData").Comment = ""
End Sub

Do you want to set the comment to "" or to remove the comment? Please include the error message you receive next time.
To remove:
If Not (ActiveWorkbook.Names("VendorData").Comment is Nothing) then ActiveWorkbook.Names("VendorData").Delete
To add/modify the text of a comment:
ActiveWorkbook.Names("VendorData").Comment.Text ""

Related

copying the rows one below another checking on the last filled column

I have a sheet List. I want the contents of list to be transferred to my sheet Evaluation. But my evaluation sheet, already consist of the previous evaluation. I want the new rows just below the old ones. Can some one help how I can achieve this ?
I have the below code with me, which is a copy paste functionality.
Sub lastweekctt()
Worksheets("List").Range("A4:W1000").Copy _
Destination:=Worksheets("Evaluation").Range("A5")
End Sub
I have my header in row 4 in both the sheets.
You need to get last blank row:
Sub lastweekctt()
Dim LastRow As Long
'get last row
LastRow = Worksheets("Evaluation").Cells(Rows.Count,1).End(xlUp).Row
Worksheets("List").Range("A4:W1000").Copy _
Destination:=Worksheets("Evaluation").Range("A" & LastRow + 1)
End Sub
Hope this help.
You will need to find the last row first
lLastRow = Worksheets("Evaluation").Cells(Worksheets("Evaluation").Rows.Count, 1).End(xlUp).Row
and then your destination range will look like this
.Range("A" & lLastRow + 1)

Find last row, select specific column in row

I'm just starting to learn VBA and I've tried to find solutions here but to no avail. I'm seeking a VBA macro for this:
I have a sheet in my workbook called LOG that gets a timestamp in column A when I start to fill the row. Once I've completed a task I use =CONCATENATE in column I to summarize the rows A through H. Column I has the formula content filled down to row 300 or more. Column A is blank until I enter a time-stamp
( "ctrl + :" ).
What I am seeking to do is run a macro through a command button where it will find the last timestamped row in column A, and then select and copy contents (not the formula) of that row in column I to clipboard.
I've tried to modify so many different suggestions I've found in stackoverflow but with little success. I'm not sure really what I'm doing wrong and I've tried so many of them I don't know which I would share with you for an example. Any help would be very appreciated! Thanks again!
1) Define a function to copy some text to the clipboard:
Sub CopyText(Text As String)
'VBA Macro using late binding to copy text to clipboard.
'By Justin Kay, 8/15/2014
Dim MSForms_DataObject As Object
Set MSForms_DataObject = CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
MSForms_DataObject.SetText Text
MSForms_DataObject.PutInClipboard
Set MSForms_DataObject = Nothing
End Sub
Then something like this:
Sub GetLastTimestampAndCopy()
dim ws as worksheet
dim strValue as string
dim lngLastRow as long
set ws = Activeworkbook.Worksheets("LOG")
' Get the last populated cell in the first column
lngLastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
' Get corresponding value in the same row but in column I
strValue = ws.Cells(lngLastRow, 9).Value
CopyText strValue
End Sub
Execute the second SUB and you should have the value on your clipboard.

Macro for copying a specific Row of formulas into newly created rows

I recently posted a question, and unfortunately did not get very far with any answers. I have re-worked my macro to mirror a similar scenario I found elsewhere. The problem is I am now getting stuck at the very end.
Purpose of the macro:
1. Beneath the selected cell, I need to insert x new rows = entered months -1
In the first inserted row, I need a set of relative formulas that can be found in the Actual Row 2 of the current worksheet (basically copy and paste row 2 into the first row created)
In the subsequent inserted rows, I need a set of relative formulas that can be found in the Actual Row 3 of the current worksheet
As is, the macro does what I want, except I don't know how to paste row 3 in all subsequent rows. I'm assuming I need some conditional statement?
As mentioned in my last post, I am trying to teach myself VBA, so any help would be appreciated!!
Sub InsertMonthsAndFillFormulas(Optional vRows As Long = 0)
Dim x As Long
ActiveCell.EntireRow.Select 'So you do not have to preselect entire row
If vRows = 0 Then
vRows = Application.InputBox(prompt:= _
"Enter the total number of months in the program", Title:="Add Months", _
Default:=1, Type:=1) 'Default for 1 row, type 1 is number
If vRows = False Then Exit Sub
End If
Dim sht As Worksheet, shts() As String, i As Long
ReDim shts(1 To Worksheets.Application.ActiveWorkbook. _
Windows(1).SelectedSheets.Count)
i = 0
For Each sht In _
Application.ActiveWorkbook.Windows(1).SelectedSheets
Sheets(sht.Name).Select
i = i + 1
shts(i) = sht.Name
x = Sheets(sht.Name).UsedRange.Rows.Count 'lastcell fixup
Selection.Resize(rowsize:=2).Rows(2).EntireRow. _
Resize(rowsize:=vRows - 1).Insert Shift:=xlDown
Rows(2).EntireRow.Copy Destination:=Selection.Offset(1).Resize( _
rowsize:=1)
Rows(3).EntireRow.Copy Destination:=Selection.Offset(2).Resize( _
rowsize:=1)
On Error Resume Next
Next sht
Worksheets(shts).Select
End Sub
Ok, based on your comments, the below code should meet your needs. But first, a few things to note.
I've added several comments to help you understand what is happening in the code.
Based on your comment regarding vRows, the code will now terminate if the user keeps the default input box value ("1"). The logic is that if the value is only one, then no rows need to be added. Notice that I subtract 1 from the Inputbox value.
The code assumes you have headers or at least filled cells in row one. I use row one to find the last used column.
If there's any chance that the wrong sheet can be active when this code is executed, uncomment line 16 of my code. (Obviously you'd need to change the code to reflect your sheet's name.
Finally, this code assumes that the upper-left corner of your dataset is in A1.
Tested on Sample Dataset
Sub InsertMonthsAndFillFormulas(Optional vRows As Long = 0)
Dim lastCol As Long
Dim r As Range
'Ask user for number of months.
'If the user keeps the default value (1), exit sub.
If vRows = 0 Then
vRows = Application.InputBox(prompt:= _
"Enter the total number of months in the program", Title:="Add Months", _
Default:=1, Type:=1) - 1
If vRows = 0 Then Exit Sub
End If
'Uncomment this line if you are concerned with which sheet needs to be active.
'ThisWorkbook.Sheets("YourSheet").Select
With ActiveSheet
'Set the range to work with as the cell below the active cell.
Set r = ActiveCell.Offset(1)
'Find the last used column. (Assumes row one contains headers)
'Commented this out to hard-code the last column.
'lastCol = .Rows("1:1").Find("*", searchdirection:=xlPrevious).Column
'Insert the new rows.
r.EntireRow.Resize(vRows).Insert Shift:=xlDown
'r needs to be reset since the new rows pushed it down.
'This time we set r to be the first blank row that will be filled with formulas.
Set r = .Range(.Cells(ActiveCell.Offset(1).Row, 1), _
.Cells(ActiveCell.Offset(1).Row, "H")) '<~~ Replaced lastCol with "H"
'**Add formulas to the new rows.**
'Adds row two formulas to the first blank row.
.Range(.Cells(2, 1), .Cells(2, "H")).Copy r
'Adds row three formulas to the rest of the blank rows.
.Range(.Cells(3, 1), .Cells(3, "H")).Copy r.Offset(1).Resize(vRows - 1)
End With
End Sub
Edit
The variable lastCol is what defines the right most column to copy formulas from. This variable is set using column headers in row 1. I prefer using variables like this to make the code more robust (i.e. you can add a column to your dataset without breaking the macro), however, for this to work you need headers above every used column (or at least cells that contain values).
If you aren't concerned with adding more columns in the furture, you can hard-code the last column into the code (see my revisions).

Excel Macro find last column used, insert new column and copy formulas from previous

I am trying to create an "Insert Column" macro in Excel.
The workbook uses formulas and conditional formatting to display progress along a timeline. I need to provide users with a way to add additional columns to the timeline.
The macro I am trying to build locates the last column and copies the entirety of column lastColumn into column newColumn. However, everything that I find online and try to adapt either gives me an object error or doesn't do anything. Please help me figure out how to do this.
Here's my code so far.
Sub InsertColumn()
Dim lastColumn As Long
Dim newColumn As Long
With ActiveSheet
lastColumn = .Range("A1").SpecialCells(xlCellTypeLastCell).column
End With
newColumn = lastColumn + 1
Selection.AutoFill Destination:=Columns(lastColumn & ":" & newColumn), Type:=xlFillDefault
End Sub
If you are simply trying to copy the one column to another then this will work:
Sub InsertColumn()
Dim lastColumn As Long
lastColumn = ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Column
Columns(lastColumn).Copy Destination:=Columns(lastColumn + 1)
End Sub

I need a VBA code to count the number rows, which varies from ss to ss, return that number and copy and paste that row and all other columns

I have vba question I have been trying to find the answer for for a long time. I have numerous spreadsheets from numerous clients that I run macro's on, I'm new to coding and have been able to mostly figure out what I need to do. My clients send us data monthly and every month the number of rows change. The columns don't change but the amount of data does. My previous macro's I have just chosen the entire column to copy and paste onto our companies template. This worked fine for must things but has created some really long code and macros take a long time. I would like to write a code that counts how many rows are in a certain column and then from there copies and pastes that however many rows it counted in each column. Only a few columns contain data in every row, so I need it to count the rows in one specific column and apply to that every column. Any help would be appreciated.
Thanks
Tony
Hi Guys,
Still having issues with this, below I pasted the code I'm using if anyone can see why it won't run please help.
Windows("mmuworking2.xlsx").Activate
Workbooks.Open Filename:= _
"C:\Users\I53014\Desktop\QC DOCS\Sample_Data_Import_Template.xlsx"
Windows("mmuworking2.xlsx").Activate
Dim COL As Integer
COL = Range("A:DB").Columns.Select
**Range(Cells(2, COL), Cells(Range("E" & Rows.Count).End(xlUp).Row, COL)).Copy Destination:=Windows("Sample_Data_Import_Template.xlsx").Range("A2")**
Range("A2").Paste
Range("A5000").Formula = "='C:\Users\I53014\Desktop\[Import_Creator.xlsm]sheet1'!$B$2"
ActiveWorkbook.SaveAs Filename:="Range (A5000)", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
I bolded where it keeps stopping.
This should give you the last row containing data:
ActiveSheet.UsedRange.Rows.Count
This will give you the last row in a specific column:
Range("B" & Rows.Count).End(xlUp).Row
here is an example of how I can copy every row in the first three columns of a worksheet
Sub Example()
Dim LastRow As Long
LastRow = ActiveSheet.UsedRange.Rows.Count
Range(Cells(1, 1), Cells(LastRow, 3)).Copy Destination:=Sheet2.Range("A1")
End Sub
You have to be careful as there are some caveats to both methods.
ActiveSheet.UsedRange may include cells that do not have any data if the cells were not cleaned up properly.
Range("A" & Rows.Count).End(xlUp).Row will only return the number of rows in the specified column.
Rows(Rows.Count).End(xlUp).Row will only return the number of rows in the first column.
Edit Added an example
Edit2 Changed the example to be a bit more clear
For this example lets say we have this data
You could copy any other column down to the number of rows in column A using this method:
Sub Example()
Dim Col as Integer
Col = Columns("C:C").Column
'This would copy all data from C1 to C5
'Cells(1, Col) = Cell C1, because C1 is row 1 column 3
Range(Cells(1, Col), Cells(Range("A" & Rows.Count).End(xlUp).Row, Col)).Copy Destination:=Sheet2.Range("A1")
End Sub
The end result would be this: