Create rows and merge the first three columns - excel

I'd like to have button in excel that insert a row and then merge the first three columns as well.
below is my code. It makes the row but it doesn not merge the columns. I just started VBA today so I assume it might be a syntax error.
Can someone assist pls?
Cheers
my vba code:
Sub AddRow()
Dim rowNum As Integer
On Error Resume Next
rowNum = Application.InputBox(Prompt:="Enter Row Number where you want to add a row:", _
Title:="VCRM")
Rows(rowNum & ":" & rowNum).Insert Shift:=xlDown
Range("A(rowNum):A(rowNum + 1)").Merge False
End Sub

You can try this one too.
This function accepts only numeric values for the row number. If you enter any other character, the pop up box will say, "Number is not valid", and the InputBox will stay and not end the function until you enter a number (you can click on x if you want to cancel).
Sub add_rows()
row_number = Application.InputBox(Prompt:="Enter Row Number where you want to add a row:", _
Title:="VCRM", Type:=1)
ThisWorkbook.Sheets("Sheet1").Rows(row_number).Insert
Rng = "A" & row_number & ":" & "C" & row_number
ThisWorkbook.Sheets("Sheet1").Range(Rng).Merge
ThisWorkbook.Sheets("Sheet1").Range(Rng).HorizontalAlignment = xlCenter
End Sub

Something like this:
Sub AddRow()
Dim ws As Worksheet, rowNum As Long 'use Long instead of Integer
On Error Resume Next 'ignore error if user doesn't enter a number
rowNum = Application.InputBox(Prompt:="Enter Row Number where you want to add a row:", _
Title:="VCRM")
On Error GoTo 0 'stop ignoring errors
If rowNum = 0 Then
MsgBox "A numeric value is required!", vbExclamation
Exit Sub
End If
Set ws = ActiveSheet
ws.Rows(rowNum).Insert Shift:=xlDown
ws.Cells(rowNum, "A").Resize(1, 3).Merge
End Sub

Related

How to run through columns and rows of a table in excel with vba

I am currently working on writing a data verification makro. Currently, it runs through one column and throws an error if the wrong data type is entered. The columns are dynamic because there will be new entries.
How do I run this code through several columns not only one?
Sub checken()
Dim i As Integer
Range("D4").Select
Do Until IsEmpty(ActiveCell)
If IsNumeric(ActiveCell) = False Then
MsgBox ("A number has to be entered " & "row " & ActiveCell.Row)
End If
ActiveCell.Offset(1, 0).Select
Loop
End Sub
You can try below sub-
Sub CheckColumns()
Dim rng As Range
Dim lCol As Long, lRow As Long
lCol = Range("D4").End(xlToRight).Column
lRow = Range("D4").End(xlDown).Row
For Each rng In Range("D4", Cells(lRow, lCol))
If IsNumeric(rng) = False Then
MsgBox ("A number has to be entered " & "row " & rng.Row)
End If
Next rng
End Sub

How do I Offset Rows correctly to Find the highest number in a Column in VBA?

I'm trying to run this code in VBA to find out which row has the highest number in column 'A'? But it's not working. Can someone help please? Below is the Code:
Sub ForNextDemo()
Dim MaxVal As Double
Dim Row As Long
MaxVal = WorksheetFunction.Max(Range("A:A"))
For Row = 1 To Rows.Count
If Range("A1").Offset(1, 0).Value = MaxVal Then
Range("A1").Offset(1, 0).Activate
MsgBox "Maximum Value is in" & Row
Exit For
End If
Next Row
End Sub
Your code fails because you check always the same cell. No matter which value row has, Range("A1").Offset(1, 0) will always check cell A2 (1 row below A1)
What you mean is probably something like Range("A1").Offset(row, 0)
However, there is a much easier (and faster) way to get the row with the maximum value, using the Match-function.
An advice: You should tell VBA always which sheet is should use. When you write Range(A1), it will use the current active sheet. This is not always what you want. Instead, use for example ThisWorkbook.Sheets(1) (first sheet of the workbook where the code is stored). You can also use the sheet name, eg ThisWorkbook.Sheets("Sheet1")
Dim MaxVal As Double
Dim Row As Long
With ThisWorkbook.Sheets(1)
Dim r As Range
Set r = .Range("A:A")
MaxVal = WorksheetFunction.max(r)
Row = WorksheetFunction.Match(MaxVal, r, 0)
Debug.Print "The maximum value is " & MaxVal & " and it is found in row " & Row
End With
Get the Maximum and the Row of Its First Occurrence
You can avoid the loop if there are no error values in the column.
Sub ForNextDemo()
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
Dim MaxVal As Variant ' could be an error value
Dim MaxRow As Long
With ws.Range("A:A")
If Application.Count(.Cells) = 0 Then
MsgBox "There are no numbers in the column.", vbCritical
Exit Sub
End If
MaxVal = Application.Max(.Cells)
If IsError(MaxVal) Then
MsgBox "There are error values in the column.", vbCritical
Exit Sub
End If
MaxRow = Application.Match(MaxVal, .Cells, 0)
' Select and scroll to the first 'max' cell.
Application.Goto .Cells(MaxRow), True
End With
MsgBox "The maximum value is " & MaxVal & "." & vbLf _
& "Its first occurrence is in row " & MaxRow & ".", vbInformation
End Sub

How to add blank rows below selected cell and keep formatting and formulas of above

Sub addRows()
' Adds new blank lines based on user input, keeping formatting and formulas of above.
Dim numRows As Long
Dim raSource As Range
Dim bResult As Boolean
Set raSource = ActiveCell.EntireRow
numRows = InputBox("Enter number of rows to insert. Rows will be added above the highlighted row.")
On Error Resume Next
raSource.Copy
bResult = Range(raSource.Offset(1, 0), raSource.Offset(numRows,
0)).EntireRow.Insert(Shift:=xlShiftDown, CopyOrigin:=xlFormatFromLeftOrAbove)
Application.CutCopyMode = False
If Not bResult Then
MsgBox "Inserting rows failed!", vbExclamation
End If
End Sub
The code works how I want it to except it keeps all the data from the selected row and pastes it to new rows. I want to only keep the formatting and formulas of the selected row and insert the new row below.
Try this code. I have linkedan example workbook as well. Let me know if this works.
Download example workbook here
Sub insertXRows()
Dim cell As Range
Dim lngRows As Long
Application.ScreenUpdating = False
'ERROR HANDLER
On Error GoTo ErrMsg
'#CHECK IF ACTIVE CELL IS IN A TABLE
'SOURCE: https://stackoverflow.com/a/34077874/10807836
Dim r As Range
Dim lo As ListObject
Set r = ActiveCell
Set lo = r.ListObject
If Not lo Is Nothing Then
Select Case lo.Name
Case "Table1"
If r.Row = lo.Range.Row Then
MsgBox "In Table1 Header"
Else
MsgBox "In Table1 Body"
End If
Case "SomeOtherTable"
'...
End Select
Else
MsgBox "Active cell is not in any table. Please select a cell in an active table and retry."
Exit Sub
End If
'MSGBOX to enter #rows to insert
lngRows = InputBox("Enter number of rows to insert. Rows will be added above the highlighted row.")
'CODE TO INSERT X Rows
Selection.Resize(lngRows).EntireRow.Insert
For Each cell In Intersect(ActiveSheet.UsedRange, Selection.Offset(-1, 0).EntireRow)
If cell.HasFormula Then
cell.Copy cell.Offset(1, 0)
End If
Next
Application.ScreenUpdating = True
'ERROR MSG
On Error GoTo 0
Exit Sub
ErrMsg: MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure insertX, line " & Erl & "."
End Sub

Excel VBA: How do I add text to a blank cell in a specific column then loop to the next blank cell and add text?

I need a macro to add text to blank cells in Column A. The macro needs to skip cells that have text. The macro needs to stop looping at the end of the data set.
I am trying to use an If Else statement, but I think I'm on the wrong track. My current, non-working code is below. Thank you so much - I'm still new to VBA
Sub ElseIfi()
For i = 2 To 100
If Worksheets("RawPayrollDump").Cells(2, 1).Value = "" Then
Worksheets("RawPayrollDump").Cells(2, 1).Value = "Administration"
Else if(not(worksheets("RawPayrollDump").cells(2,1).value="")) then 'go to next cell
End If
Next
End Sub
To find the last row of data, use the End(xlUp) function.
Try this code. It replaces all empty cells in column A with Administration.
Sub ElseIfi()
Set ws = Worksheets("RawPayrollDump")
lastrow = ws.Cells(Rows.Count, 1).End(xlUp).Row ' last data row
For i = 2 To lastrow ' all rows until last data row
If ws.Cells(i, 1).Value = "" Then ' column A, check if blank
ws.Cells(i, 1).Value = "Administration" ' set text
End If
Next
End Sub
There is no need to loop. Please try this code.
Sub FillBlanks()
Dim Rng As Range
With Worksheets("RawPayrollDump")
Set Rng = Range(.Cells(2, "A"), .Cells(.Rows.Count, "A").End(xlUp))
End With
On Error Resume Next
Set Rng = Rng.SpecialCells(xlCellTypeBlanks)
If Err Then
MsgBox "There are no blank cells" & vbCr & _
"in the specified range.", _
vbInformation, "Range " & Rng.Address(0, 0)
Else
Rng.Value = "Administration"
End If
End Sub
Replace Blanks feat. CurrentRegion
Range.CurrentRegion
Since OP asked for "... stop looping at the end of the data set. ",
I've written this CurrentRegion version.
As I understand it, the end of the data set doesn't mean that there
cannot be blank cells below the last cell containing data in column
A.
Use the 1st Sub to test the 2nd, the main Sub (replaceBlanks).
Adjust the constants including the workbook (in the 1st Sub) to fit your needs.
Criteria is declared as Variant to allow other data types not just strings.
The Code
Option Explicit
Sub testReplaceBlanks()
Const wsName As String = "RawPayrollDump"
Const FirstCellAddress As String = "A2"
Const Criteria As Variant = "Administration"
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
replaceBlanks ws, FirstCellAddress, Criteria
End Sub
Sub replaceBlanks(Sheet As Worksheet, _
FirstCellAddress As String, _
Criteria As Variant)
' Define column range.
Dim ColumnRange As Range
Set ColumnRange = Intersect(Sheet.Range(FirstCellAddress).CurrentRegion, _
Sheet.Columns(Sheet.Range(FirstCellAddress) _
.Column))
' To remove the possibly included cells above the first cell:
Set ColumnRange = Sheet.Range(Range(FirstCellAddress), _
ColumnRange.Cells(ColumnRange.Cells.Count))
' Note that you can also use the addresses instead of the cell range
' objects in the previous line...
'Set ColumnRange = sheet.Range(FirstCellAddress, _
ColumnRange.Cells(ColumnRange.Cells.Count) _
.Address)
' or a mixture of them.
' Write values from column range to array.
Dim Data As Variant
If ColumnRange.Cells.Count > 1 Then
Data = ColumnRange.Value
Else
ReDim Data(1 To 1, 1 To 1): Data(1, 1) = ColumnRange.Value
End If
' Modify array.
Dim i As Long, k As Long
For i = 1 To UBound(Data)
If IsEmpty(Data(i, 1)) Then Data(i, 1) = Criteria: k = k + 1
Next i
' Write modified array to column range.
' The following line is used when only the first cell is known...
'Sheet.Range(FirstCellAddress).Resize(UBound(Data)).Value = Data
' ...but since the range is known and is the same size as the array,
' the following will do:
ColumnRange.Value = Data
' Inform user.
If k > 0 Then GoSub Success Else GoSub Fail
Exit Sub
' Subroutines
Success:
MsgBox "Wrote '" & Criteria & "' to " & k & " previously " _
& "empty cell(s) in range '" & ColumnRange.Address & "'.", _
vbInformation, "Success"
Return
Fail:
MsgBox "No empty cells in range '" & ColumnRange.Address & "'.", _
vbExclamation, "Nothing Written"
Return
End Sub

VBA Inbut box with loop

I have just started learning VBA (and coding in general) and I am faced with a problem to which I have not yet found a solution. I'd like to create an input box with a loop so that the output from the input box will be printed to separate cell. For example, I would like to write number "5" to the input box and the output will be printed to Cell "A1" and the next input, say number "9", will be printed to Cell "A2".
So far, I have managed to this and everything works fine except the last row as I don't know how to continue from here.
Private Sub CommandButton1_Click()
Dim myValue As Variant
myValue = InputBox("Please insert number")
Range("A1").Select
ActiveCell.Value = myValue
Range(ActiveCell) = Range(ActiveCell) + 1
End Sub
All help is appreciated
Try with below code
Private Sub CommandButton1_Click()
Dim myValue As Variant
myValue = InputBox("Please insert number")
Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = myValue
End Sub
EDIT #1:
Updated the code as per the advice of user3598756
Private Sub CommandButton1_Click()
Dim myValue As Variant
myValue = InputBox("Please insert number")
If Range("A" & Range("A" & Rows.Count).End(xlUp).Row).Value = "" Then
Range("A" & Range("A" & Rows.Count).End(xlUp).Row) = myValue
Else
Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = myValue
End If
End Sub
edited to
shorten the code
add solution should cell "A1" be already filled with header
the following code will do:
Sub CommandButton1_Click()
With Cells(Rows.Count, 1).End(xlUp)
.Offset(IIf(.Value <> "", 1, 0)) = InputBox("Please insert number")
End With
End Sub
where the "conditional" offset is necessary to manage the first empty cell being in row 1 (no offset) or lower (1 row offset)
should cell "A1" be already filled with header, the code shortens down to:
Sub CommandButton1_Click()
Cells(Rows.Count, 1).End(xlUp).Offset(1) = InputBox("Please insert number")
End Sub
If you want to do a loop - for example 10 times - then you can use this example code:
Sub CommandButton1_Click()
Dim counter As Integer
Dim myValue As Variant
For counter = 1 To 10
myValue = InputBox("Please insert number")
Sheets("Sheet1").Cells(counter, 1).Value = myValue
Next counter
End Sub

Resources