Make sure you use Option Explicit
to detect variable typos.
Make sure every Range
, Cells
, Rows
and Colums
object has a worksheet referenced like ws.Range
, otherwise it will take whatever sheet is active (and that can easily change by a user click).
As you can see in the documentation of the Range.Find method it is absolutely secessary that you specify the folowing 4 parameters or you get random results:
The settings for LookIn
, LookAt
, SearchOrder
, and MatchByte
are saved each time you use this method. If you do not specify values
for these arguments the next time you call the method, the saved
values are used. Setting these arguments changes the settings in the
Find dialog box, and changing the settings in the Find dialog box
changes the saved values that are used if you omit the arguments. To
avoid problems, set these arguments explicitly each time you use this
method.
Without defining these parameters it might work now and stop working another time.
After using the Find()
method make sure you test if something was found If Not FoundAt Is Nothing Then
or it will erorr.
The [ ]
you use in [celladdress]
have nothing to do with the [A1]
notation and do not work like you assumed. They need to be removed!
Declare your variables as close as possible to their first use instead of the very top. Otherwise you will easily end up with something like Dim v As Integer
and never using v
in the entire code.
Finally use proper formatting of the code and proper indentation. The easier the code is readable the less errors you will make and the easier it is to debug. Don't work like "I will fix formatting later". This will slow you down in writing good code and you probably will never fix it.
So you end up with something like:
Option Explicit
Public Sub Example()
Dim ws As Worksheet
Set ws = Worksheets("Sheet1") 'define your sheet
Dim LastRow As Long
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Offset(1, 0).Row
ws.Cells(LastRow, 13).Value = "Sampling"
ws.Range("C3").Copy ws.Range("C" & LastRow)
ws.Range("B3").Copy ws.Range("B" & LastRow)
ws.Range("A3").Copy ws.Range("A" & LastRow)
Dim FoundAt As Range 'define ALL these parameters below to prevent random/wrong results
Set FoundAt = ws.Range("G3:G1000").Find(What:="Description", LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, MatchByte:=False)
If Not FoundAt Is Nothing Then 'test if something was found you cannot delete if you found nothing
Dim CellAddress As String
CellAddress = FoundAt.Offset(-1, 30).Address
ws.Range("A2", CellAddress).Delete
Else
MsgBox "'Description' was not found.", vbCritical
End If
End Sub