I'm trying to auto fill a row of formulas to the row before it.
I'm on excel 2010. I know that the ranges I'm using in the autofill function are the right ranges, I checked by adding in the select function and going line by line to make sure it selected the right ones.
Sub NewIC()
Dim v As Range, newV As Range, oldVRow As Range, newVRow As Range
Dim s As Range
Dim dc As Range
With Sheets("Charts").Cells
'Inserting name into Vios
Set v = .Find("Vios", LookIn:=xlValues)
If Not v Is Nothing Then
v.Select
ActiveCell.Offset(4, 0).Select
With Selection.EntireRow.Insert(xlShiftDown, xlFormatFromRightOrBelow)
Set newV = ActiveCell
Range("T1").Copy newV
newV.Font.Bold = True
End With
End If
'Dragging up formulas
Set oldVRow = Range(newV.Offset(-1, 1), newV.Offset(-1, 8))
Set newVRow = Range(newV.Offset(0, 1), newV.Offset(0, 8))
oldVRow.Select
newVRow.Select
newVRow.AutoFill Destination:=oldVRow, Type:=xlFillDefault
End With
End Sub
All of the code works up until the last line. It sets the right cell as newV, sets the right ranges, but I get the error
Run-time error '1004' AutoFill method of Range class failed
Modify:
Set newVRow = Range(newV.Offset(0, 1), newV.Offset(0, 8))
to include the row above:
Set newVRow = Range(newV.Offset(-1, 1), newV.Offset(0, 8))
and change:
newVRow.AutoFill Destination:=oldVRow, Type:=xlFillDefault
to:
oldVRow.AutoFill Destination:=newVRow, Type:=xlFillDefault
You don't need to use all this Select:
'oldVRow.Select ' comment this row
'newVRow.Select ' comment this row
Related
Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 3).Select
Dim Q As String
Q = ActiveCell.Address
Range(" Q:D10438").Select
Selection.ClearContents
The Variable Q is taking the value of the active cell, but i am unable to include it in range
The variable cannot be included in the quotes. Also you should avoid using Select. A simpler version would be:
Dim Q As String
Q = Range("A1").End(xlDown).Offset(0, 3).Address
Range(Q & ":D10438").ClearContents
Range Object
How to avoid using Select
When defining a range from two cells, the Range object 'allows' us to use cell range objects or cell range addresses or a mix of them:
Dim rng as range
Set rng = Range("A1","D4")
Set rng = Range(Range("A1"), Range("D4"))
' Mix
Set rng = Range("A1", Range("D4"))
Set rng = Range(Range("A1"), "D4")
to get the range:
$A$1:$D$4
We can apply the second 'mix solution' to the question:
' First cell range
Range("A1").End(xlDown).Offset(0, 3)
' Second cell address
"D10438"
to get the result:
Range(Range("A1").End(xlDown).Offset(0, 3), "D10438").ClearContents
After inserting a Table into Excel, I want to change the Table Style. However, it's not changing the style.
How do I use the 'Apply and Clear Formatting' function in VBA?
For Each ws In ActiveWorkbook.Worksheets
With ws
If .Index <> 1 Then
'Insert Table with the Data starting in Column A, Row 3
Dim myTable As ListObject
Set myTable = .ListObjects.Add(xlSrcRange, .Range("A3", .Range("A3").End(xlToRight).End(xlDown)), , xlYes)
With myTable
.Name = .Name & "_Table"
.TableStyle = "TableStyleMedium12"
.Range.Font.Bold = True
.Range.Font.Size = 16
End With
In Excel, a cell is defined by its coordinates, like A3. The corresponding VBA syntax is Cells(3, "A") or better still, Cells(3, 1).
In Excel, a range is defined by its first and last cell, like A3:D12. In VBA the same is expressed like Range(Cells(3, "A"), Cells(12, "D")) or - more proficient - Range(Cells(3, 1), Cells(12, 4)). Prefer numbers to define columns because they can be calculated. Excel can find Columns(3 + 4) but it can't find Columns("C" + 4).
Cells(Rows.Count, "A") defines a single cell which is equal to Cells(1048576, 1). It's the last possible cell in column A. Similarly, Cells(3, Columns.Count) defines a cell at the extreme right of row 3. Columns.Count = 16384 but might be a smaller number in worksheets created with earlier versions of Excel.
The combination of either of the above expressions with .End(xlUp) or End.(xlToLeft) just describes an offset from the cell already defined, to look for the first occupied cell (the End), either up or To[the]Left. Therefore these expressions define a single cell. They wouldn't even define a range if they were presented as first and last cell of a range in proper syntax. This, Range("A3", .Range("A3").End(xlToRight).End(xlDown)), isn't proper syntax.
In the code below I have taken pains to take you through the process of defining the range for your table in small steps. It works, and that's great. But the point is that it should work for you, and it will only do that if you fully understand it. I hope the above explanation helps toward that end.
Sub InsertTable()
' 026
Dim Ws As Worksheet
Dim Tbl As ListObject
Dim Rng As Range ' range in which to set the table
Dim Rl As Long ' last row
Dim Cl As Long ' last column
For Each Ws In ActiveWorkbook.Worksheets
With Ws
If .Index > 1 Then
' find the last used row in column A
Rl = .Cells(.Rows.Count, "A").End(xlUp).Row
' find the last used column in row 3
Cl = .Cells(3, .Columns.Count).End(xlToLeft).Column
' set the range for the table
Set Rng = .Range(.Cells(3, "A"), .Cells(Rl, Cl))
' convert the range to a table
Set Tbl = .ListObjects.Add(xlSrcRange, Rng, , xlYes)
End If
End With
With Tbl
.Name = .Name & "_Table"
.TableStyle = "TableStyleMedium12"
.Range.Font.Bold = True
.Range.Font.Size = 16
End With
Next Ws
End Sub
I need to convert the column with Dates, formatted in Date formats into text format and if possible in reverse.
I can apply worksheet function TEXT, fill down by copy pasting or double clicking and then copy/cut the helper column and paste as value in the original column and record the macro, but is there any way to do so without selecting/activating, autofilling, using helper columns,(like "H" and "I") in this example? Will any vba function in place of worksheet function result in more efficiency?
Sub DateFormatToText()
Range("H2").Select
ActiveCell.FormulaR1C1 = "=TEXT(RC[-1],""dd/mm/yyyy"")"
Range("H2").Select
Selection.AutoFill Destination:=Range("H2:H20")
End Sub
Browsing through, I came to know those are not optimal codes.
You can try like below:
Range("H2:H" & Range("G" & Rows.Count).End(xlUp).Row).Formula = "=TEXT(G2,""dd/mm/yyyy"")"
With no helper columns, no worksheet formulas
To change the date entries in the same column, something like:
Option Explicit
Sub colGtoText()
Dim v, i As Long, r As Range, ws As Worksheet
'define the working area of Column G entries
Set ws = ThisWorkbook.Worksheets("sheet1")
With ws
Set r = .Range(.Cells(1, "G"), .Cells(.Rows.Count, "G").End(xlUp))
v = r.Value 'read into vba array for faster processing
End With
With r
.NumberFormat = "#" 'change to text format
'process each entry to the appropriately formatted text string
For i = 1 To UBound(v)
If IsDate(v(i, 1)) Then v(i, 1) = Format(v(i, 1), "mm/dd/yyyy")
Next i
'write results back to the range from the vba array
.Value = v
End With
End Sub
=TEXT(G2,"dd-mm-yyyy")
used - operation either using Replace function
Can anyone help me adjust this code to fix my solution?
I have a button that adds x amount of new rows from A5 downwards. Columns A - Z.
I would like the new rows to be blank but still contain dropdowns and formula. New to VBA and struggling with this one.
I think I need to change the range and add xlPasteFormulas but unsure where and how for both. Any help hugely appreciated.
Option Explicit
Sub AddRows()
Dim x As Integer
x = InputBox("How many rows would you like to add?", "Insert Rows")
'Selecting range to insert new cells
Range(Cells(5, 1), Cells(x + 4, 1)).EntireRow.Insert
'Copys current cell A6 and past in the new cells
Cells(x + 5, 1).Copy Range(Cells(5, 1), Cells(x + 4, 1))
'if you want the cells to be blank but still have the drop down options
Range(Cells(5, 1), Cells(x + 4, 1)).ClearContents
End Sub
Please try the code below. It will copy everything from the BaseRow and then delete constant values in that range, leaving formats, including data validations, and formulas.
Sub AddRows()
Const BaseRow As Long = 11 ' modify to suit
Dim x As String ' InputBox returns text if 'Type' isn't specified
Dim Rng As Range
Dim R As Long
x = InputBox("How many rows would you like to add?", "Insert Rows")
If x = "" Then Exit Sub
R = BaseRow + CInt(x) - 1
Rows(BaseRow).Copy 'Copy BaseRow
'specify range to insert new cells
Set Rng = Range(Cells(BaseRow, 1), Cells(R, 1))
Rng.Insert Shift:=xlDown
' insert the new rows BEFORE BaseRow
' to insert below BaseRow use Rng.Offset(BaseRow - R)
Set Rng = Rng.Offset(BaseRow - R - 1).Resize(Rng.Rows.Count, ActiveSheet.UsedRange.Columns.Count)
Rng.Select
On Error Resume Next
Rng.SpecialCells(xlCellTypeConstants).ClearContents
Application.CutCopyMode = False '
End Sub
The code now has an emergency exit: If you don't enter anything in the InputBox the procedure terminates. Note that new rows are inserted above the BaseRow. After the insertion all new rows and the old row are identical. You can then choose to retain the constants in either the first or the last of these rows, effectively meaning, insert new, blank rows either above or below the BaseRow.
I got this problem:
I am using VBA, to make some charts.
I made some input fields...those input fields are transferred via button to a table, and from that table, I draw the line chart.
Looks like this:
Answers in column D, they are all changeable, but the number is constant, always 12...
Then I got the table, where on button press, the answers are transferred:
Point is, on button click, I add a new row to the table, the last rows (from S to AB) are generic data, which I make with formulas out of the answers.
Once I add the new row, I also add the time stamp to the left side...
Now, I am ready to make a line chart...with the last 4 columns Y, Z, AA and AB
I made it, but I don't know how to add the timestamp to be on the x axis.
Timestamp looks like this:
Here is the code of my button:
Sub AddData()
'
' AddData Macro
' Adds data to the table
'
' Keyboard Shortcut: Ctrl+d
'
Dim cellValue As Variant
Dim rowSize As Integer
Dim i As Integer
Dim myRange As Variant
Dim cell As Variant
Dim column_Position As Integer
Dim row_Position As Integer
Dim rangeFormula As Variant
rowSize = 12
row_Position = -1
Set myRange = range("G1:G1000")
'Find first empty row
For Each cell In myRange
If IsEmpty(cell.Value) Then
column_Position = cell.Column
row_Position = cell.row
Exit For
End If
Next cell
'Do for loop and fill the cells from G(7) to R(18) with data
For i = 1 To rowSize
cellValue = range("D2:D13").Cells(i).Value
range(Cells(row_Position, "G"), Cells(row_Position, "R")).Cells(i).Value = cellValue
Next i
'Copy formulas one row bellow, from S(19) to AB(28)
If row_Position > 4 Then
range(Cells(row_Position - 1, "S"), Cells(row_Position - 1, "AB")).Select
Selection.Copy
range(Cells(row_Position, "S"), Cells(row_Position, "AB")).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks _
:=False
End If
'Add timestamp to F cells
Cells(row_Position, "F") = Now()
Cells(row_Position, "F") = Format(Now(), "dd-mm-yyyy hh:mm:ss")
'Remove Selections
Cells(1, 1).Select
Application.CutCopyMode = False
'Delete all old charts
If Not Worksheets("Data").ChartObjects.Count = 0 Then
Worksheets("Data").ChartObjects.Delete
End If
'Draw a chart
Dim rng As range
Dim cht As ChartObject
'Your data range for the chart
Set rng = ActiveSheet.range(Cells(2, "Y"), Cells(row_Position, "AB"))
'Create a chart
Set cht = ActiveSheet.ChartObjects.Add( _
Left:=ActiveCell.Left, _
Width:=775, _
Top:=275, _
Height:=250)
'Populate chart with data
cht.Chart.SetSourceData Source:=rng
'Add gridlines
cht.Chart.Axes(xlCategory).HasMajorGridlines = True
'Determine the chart type
cht.Chart.ChartType = xlXYScatterLines
cht.Activate
cht.Chart.SeriesCollection(1).XValues = "=$F$4:$F$28"
End Sub
Now, I have something like this:
A line chart with the 4 rows I used to make the chart.
But I have no idea how to add the F(F4 to last filled row) column as the x axis.
Edit1: Forgot to mention, once I add the row to the table, the current chart is deleted, and I make a new one, with the all data as before, plus the new row...
Edit2: Thanks to Pierre44, I moved the timestamp column a row higher, and added one extra row, so that the arrays all have the same length...and it looks like this:
Please help.
And it is almost done, but can you show me how to move the x axis, bellow the graph?
Like this:
Thanks.
One possible solution would be to define the whole range of your graph from the beginning:
For this you can replace:
Set rng = ActiveSheet.range(Cells(2, "Y"), Cells(row_Position, "AB"))
By:
Set rng = ActiveSheet.Range("Sheet1!$F$1:$F$" & row_Position & ",Sheet1!$Y$1:$AB$" & row_Position)
Note that I changed F4:F28 to "F1:F" & row_Position as you need to have as many values here as you have in the other columns
As your X values are quite long, you might want to change their orientation
Example:
ActiveSheet.ChartObjects("Chart").Activate
ActiveChart.Axes(xlCategory).TickLabelPosition = xlLow