Paste and on Error display msgbox using with statement - excel

I need some advice to rectify the code below. I have this code to copy paste lines to another sheet for data compilation purpose. And I'm running well using the with statement below, the problem is, when there's no data to paste, I do not know how to end the code with message box.
I see the similar question above, but how to comply the code into the With statement of VBA below?
Following is the code I read from other user, to return message box if error.
If Err Then
MsgBox "Nothing to paste!"
Err.Clear
End If
My original code, without the Message box return.
*Sub FnLstRow()
Application.ScreenUpdating = False
Dim LR As Long
ThisWorkbook.Worksheets("Data").Select
LR = Cells(Rows.Count, "AO").End(xlUp).Row
Cells(LR, 1).Offset(1, 0).EntireRow.Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
With Sheets("LatestData")
.Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues
End With
Application.CutCopyMode = False
Range("A1").Select
Application.ScreenUpdating = True
End Sub**

this is a suboptimal solution that might not work but you could try: I created a dynamic array and tried to pass your entire selection into it. If the selection had no values, it will select all of the remaining cells in the sheet, and it is likely too large to pass into the array, resulting in a run time error. I didn't touch your code except for creating the array and adding the error handling section. I hope it works lol
Sub FnLstRow()
Application.ScreenUpdating = False
Dim LR As Long
Dim Arr() As Variant
ThisWorkbook.Worksheets("Data").Select
LR = Cells(Rows.Count, "AO").End(xlUp).Row
Cells(LR, 1).Offset(1, 0).EntireRow.Select
Range(Selection, Selection.End(xlDown)).Select
On Error GoTo Handler
Arr = Selection
On Error GoTo 0
Selection.Copy
With Sheets("LatestData")
.Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues
End With
Application.CutCopyMode = False
Range("A1").Select
Application.ScreenUpdating = True
Exit Sub
Handler:
MsgBox "Nothing to paste!"
End Sub

Related

Excel vba - slow execution

I am quite inexperienced with vba and I am trying to make a code.
I am running it and it works fine but it is too slow when I have many rows. And with slow I mean that it could be running for minutes. I didnt waited till the end yet.
I would be very grateful for some help
Sub importart_lv()
Application.ScreenUpdating = False
Dim CL As Range
Dim rng As Range: Set rng = ActiveSheet.Range("A1:A2500")
For Each Cell In rng.Cells
If Cell.Value = "Position" Then
Cell.Offset(0, 6).Select
Worksheets("Bausteine").Activate
Range("G9:U9").Select
Selection.Copy
Worksheets("LV-Importieren").Activate
Selection.Insert
FindReplace
End If
'Cell.Offset(0, 11).Value = IIf(InStr(1, Cell, "Position"), "True", "")
Next
Application.CutCopyMode = False
ActiveSheet.Range("J1").Select
Worksheets("Bausteine").Activate
Range("G8:U8").Select
Selection.Copy
Worksheets("LV-Importieren").Activate
Selection.Insert
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub

Excel - VBA: Code is generating unexpected numbers (0)

I'm stuck on this, I don't understand why the code adds those extra zeros in column D; What am I doing wrong?
Code: https://pastebin.com/ccpqPJdz
last = Range("B" & Rows.Count).End(xlUp).Row
'Insert 3 columns on left. Add information in Row 1, add data in column D.
Columns("A:A").Select
Selection.Insert Shift:=xlToRight
Columns("A:A").Select
Selection.Insert Shift:=xlToRight
Columns("A:A").Select
Selection.Insert Shift:=xlToRight
Columns("E:E").Copy Destination:=Columns("C:C")
Columns("E:E").Select
Selection.Delete Shift:=xlToLeft
Range("D2:D2" & last).Select
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.FormulaR1C1 = "=R[-1]C[6]"
Columns("D").Copy
Columns("D").PasteSpecial xlPasteValues
Range("D1") = Time
Range("D1").NumberFormat = "h:mm:ss"
Input:
Output:
Avoid the Selection object. It's created as a medium of communication between the user and VBA via the screen. VBA has direct access to the Excel workbook and therefore doesn't need it. Please try this code.
Private Sub InsertThreeColumns()
Dim Rl As Long ' last used row
Dim Rng As Range
With Worksheets("NewTest") ' change to suit
Rl = .Cells(.Rows.Count, "B").End(xlUp).Row
.Columns(2).Copy
.Columns(1).Insert Shift:=xlToRight
Application.CutCopyMode = False
.Columns("A:B").Insert Shift:=xlToRight
.Columns(5).EntireColumn.Delete
On Error Resume Next
' next line will cause a crash if there are no blanks
Set Rng = .Range(.Cells(2, "D"), .Cells(Rl, "D")).SpecialCells(xlCellTypeBlanks)
If Err = 0 Then
Rng.FormulaR1C1 = "=R[-1]C[6]"
Rng.Copy
Rng.PasteSpecial xlPasteValues
End If
On Error GoTo 0
With .Cells(1, "D")
.Value = Time
.NumberFormat = "h:mm:ss"
End With
End With
End Sub
The extra zeroes that troubled you were caused by the method of defining the range where you wanted the formula to supply cell content. In your code that range is a derivative of a Selection. In the above code it's defined by starting cell and end cell. The result should be the same. It isn't because the route via the Selection object is circuitous and difficult to follow.

How do I make the cell Range work in VBA?

I have a problem with the autofill function. I want to use the macro to fill in the date until there is nothing left in B. The problem is that there are some gaps there. Can I change the code so that it fills up to the last line in B. I tried it with the code below. However, it does not work.
Sub fill()
Sheets("Table1").Select
Columns("C:C").Select
Selection.Insert Shift:=xlToRight
Range("C2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-1]="""",R[-1]C,RC[-1])"
ActiveCell.Select
Dim last As Long
Range("C2").Select
Range(Selection, Selection.End(xlToRight)).AutoFill Destination:=Range("C2:C" & last)
Selection.End(xlDown).Select
Selection.ClearContents
ActiveCell.Offset(-1, 0).Range("A1").Select
Range(Selection, Selection.End(xlUp)).Select
Selection.Copy
Range("B2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("C:C").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Range("A1").Select
End Sub
You do not need such a lengthy process. You can do it in just couple of lines. For example
rng.SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"
Here is an example. Assuming that your range is from C2 onwards as shown below.
Try this code
Option Explicit
Sub Sample()
Dim ws As Worksheet
Set ws = Sheets("Table")
Dim lRow As Long
With ws
lRow = .Range("C" & .Rows.Count).End(xlUp).Row
Dim rng As Range
Set rng = .Range("C3:C" & lRow)
Dim visibleCells As Range
On Error Resume Next
Set visibleCells = rng.SpecialCells(xlCellTypeBlanks)
On Error GoTo 0
If Not visibleCells Is Nothing Then
visibleCells.FormulaR1C1 = "=R[-1]C"
End If
End With
End Sub
In Action
Worth a Mention
Also avoid using Select/Selection/Activecell etc. You may want to read up on How to avoid using Select in Excel VBA
You do not need VBA to achieve what you want. You can achieve the same using few clicks.
NON VBA Method
Select your range. In this case C3:C13
Press CTRL + G to bring up the Go To dialog box
Click Special button
Select the Blanks radio button and click OK.
In the Formula bar type =C2 and press CTRL + ENTER key and you are done
In Action

Why am i getting this error with copy/paste?

I am getting an error
Runtime error 1004: Application defined or Object defined error
in my vba code. Could you please help me correct it?
Sub INPUT_DATA()
' INPUT_DATA Macro
' Application.ScreenUpdating = False
Application.EnableEvents = False
Sheets("Input").Select
If Range("D55").Value = 0 Then
Range("B2:AI52").Select
Selection.Copy
Sheets("Database").Select
ActiveSheet.Range("A2").End(xlDown).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
Sheets("Input").Select
MsgBox ("File has been updated. DO NOT PRESS UPDATE again, as it will enter the same data once again")
End Sub
You didn't say which line is causing the error, but it looks like it's likely this line...
ActiveSheet.Range("A2").End(xlDown).Offset(1, 0).Select
It starts at A2, and then it goes down until it finds the last used row. However, if there aren't any used rows below A2, it finds the very last row in Column A. Then it tries to offset to one row below it, which doesn't exist, and hence the error. Instead, you can find the next available row as follows...
ActiveSheet.Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Select
Although, there's no need to do all of that selecting. It's very inefficient. So your macro can be re-written as follows...
Option Explicit
Sub INPUT_DATA()
' INPUT_DATA Macro
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Dim sourceWorksheet As Worksheet
Set sourceWorksheet = Worksheets("Input")
Dim destinationWorksheet As Worksheet
Set destinationWorksheet = Worksheets("Database")
With sourceWorksheet
If .Range("D55").Value = 0 Then
.Range("B2:AI52").Copy
With destinationWorksheet
.Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues
End With
End If
End With
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
MsgBox ("File has been updated. DO NOT PRESS UPDATE again, as it will enter the same data once again")
End Sub

macro inserting new row at the bottom disables data validation

Sub InsertRow()
Dim rActive As Range
Set rActive = ActiveCell
Application.ScreenUpdating = False
With Cells(Rows.Count, "A").End(xlUp)
.EntireRow.Copy
With .Offset(1, 0).EntireRow
.PasteSpecial xlPasteAll
On Error Resume Next
.SpecialCells(xlCellTypeConstants).ClearContents
On Error GoTo 0
End With
End With
rActive.Select
Application.CutCopyMode = False
Application.ScreenUpdating = True
Application.DisplayAlerts = False
Application.DisplayAlerts = True
End Sub
My problem is, when my file is shared with others (share workbook), myself and them can save and everything and add rows, but the thing is the data validation is not copied in the new line and the drop down won't appear.
Anyone can help?
Try this. Your code worked for me so it looks like it might be something related to sharing (as per my comment).
Sub InsertRow()
Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub
With this code of #Captain Grum
Sub InsertRow()
Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End Sub
It copies now the data validation below, but the borders and formula won't copy.
Please see this picture
I'm really sorry guys. I'm really just new to programming. I now have the solution to my problems. I just have included the code of #captain grumpy and mine above. Here's the code:
Sub InsertRow()
Dim rActive As Range
Set rActive = ActiveCell
Application.ScreenUpdating = False
With Cells(Rows.Count, "A").End(xlUp)
.Offset(1, 0).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
.EntireRow.Copy
With .Offset(1, 0).EntireRow
.PasteSpecial xlPasteAll
On Error Resume Next
.SpecialCells(xlCellTypeConstants).ClearContents
On Error GoTo 0
End With
End With
rActive.Select
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub

Resources