Subtract two ranges and clear the contents from result - vba

I'm trying to subtract RangeA - RangeA+offset to get a new range. After this i need to clear all the values within it. My problem is that the variable columnrange is empty and i'm unable to realize what i'm doing wrong.
Dim rng1 As String
Dim rangeA As Range
Dim columnrange As Range
Dim clearrange As Range
rng1 = TextBoxA.Value
If Not IsNull(RangeboxA.Value) Then
On Error Resume Next
Set rangeA = Sheets("Plan1").Range(RangeboxA.Value)
rangeA.Select
Selection.Copy
rangeA.Offset(0, rng1).Select
ActiveSheet.Paste
columnrange = rangeA.Resize(rangeA.Rows.Count, rangeA.Columns.Count + rng1).Value
columnrange.Select
On Error Resume Next
If rangeA Is Nothing Then MsgBox "Verificar informação A"
End If

This code moves a user-defined range by a user-defined amount.
Sub RemoveRangeOverlap()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Plan1")
Dim rngOffset As Integer
Dim rangeA As Range, rangeB As Range
Dim cellRange() As String
On Error GoTo ErrHandle
rngOffset = CInt(TextBoxA.Value)
If RangeBoxA.Value <> "" Then
Set rangeA = ws.Range(RangeBoxA.Value) 'Set old range
cellRange = Split(CStr(RangeBoxA.Value), ":") 'Set start/ending cells
ReDim Preserve cellRange(LBound(cellRange) To UBound(cellRange))
Set rangeB = ws.Range(ws.Range(cellRange(0)).Offset(0, rngOffset), _
ws.Range(cellRange(1)).Offset(0, rngOffset)) 'set new range
rangeA.Copy rangeB 'copy new range
Application.CutCopyMode = xlCopy 'remove marching ants
If rangeA.Columns.Count <= rngOffset Then 'remove old values
rangeA.Clear
Else: ws.Range(ws.Range(cellRange(0)), _
ws.Range(cellRange(1)).Offset(0, rngOffset - rangeA.Columns.Count)).Clear
End If
Else: MsgBox "Missing target range input.", vbCritical, "Insufficient Data"
End If
ErrHandle:
If Err.Number = 438 Then
MsgBox "Invalid range format in range input box." & vbNewLine & _
"Proper range format example: A1:A1", vbCritical, "Error 438"
ElseIf Err.Number = 13 Then
MsgBox "Only numbers may be input as the range offset amount", _
vbCritical, "Error 13: Type Mis-match"
ElseIf Err.Number = 5 Then Exit Sub
Else: Err.Raise Err.Number
End If
End Sub
How the code works:
The first thing we have set up is information control from user-defined values. To accomplish this (which can also be done with If Then statements to prevent the errors from ever occurring in the first place) I've included an error handling line at the end. We know what 3 errors we expect to get depending on what the user provides us with.
Error 438 will occur if the user tries to set RangeBoxA's value as a non-range value.
Error 13 will occur if the user tries to input anything that isn't a number as the offset value.
Error 5 will occur because I'm bad at error handling and I'm not sure why it's occuring.. It loops my error statement at the end after whichever error is thrown (being a non-vba error).
Next we split up the range supplied by the user into two 'cells'. Using this we can apply some simple math to show where the copy destination will be as well as delete the proper amount of old range values.
If the number of columns is greater than the user supplied offset, then the new and old ranges will overlap. Some simple math will remove the old cells while preserving the new one's
If the number of columns is less than the user supplied offset, delete all of the old cells because they won't be overlapping.
Let me know if this works for you.

Related

Compile error: label not defined

I have a code that looks for something from the master sheet in column D such as "1x Daily" or "2x Month" (as well as others). If the cell matches a Sheet name, it gets pasted into that sheet. The problem is each row from the Master sheet is unique and therefore cannot be repeated on each sheet. Every time I run the code, it adds the rows again, so I end up with something like this
Coubourn, Stephen|A|201|Q4hours
Eudy, Donna |A|202|Q4hours
Potts, Betty |A|203|Q4hours
Coubourn, Stephen|A|201|Q4hours
Eudy, Donna |A|202|Q4hours
Potts, Betty |A|203|Q4hours
Coubourn, Stephen|A|201|Q4hours
Eudy, Donna |A|202|Q4hours
Potts, Betty |A|203|Q4hours
Below is what I have so far for this code I am trying to make, however, it isnt working. Im receiving the error message "Compile error, label not defined" on the line that says "On Error GoTo SetFirst"
Dim cell As Range
Dim cmt As Comment
Dim bolFound As Boolean
Dim sheetNames() As String
Dim lngItem As Long, lngLastRow As Long
Dim sht As Worksheet, shtMaster As Worksheet
Dim MatchRow As Variant
Set shtMaster = ThisWorkbook.Worksheets("Master Vitals Data")
ReDim sheetNames(0)
For Each sht In ThisWorkbook.Worksheets
If sht.Name <> shtMaster.Name Then
sheetNames(UBound(sheetNames)) = sht.Name
ReDim Preserve sheetNames(UBound(sheetNames) + 1)
End If
Next sht
ReDim Preserve sheetNames(UBound(sheetNames) - 1)
For Each cell In shtMaster.Range("D1:D" & shtMaster.Cells(shtMaster.Rows.Count, "D").End(xlUp).Row)
bolFound = False
MatchRow = Application.Match(cell.Offset(, -3).Value, sht.Range("A:A"), 0)
If Not IsError(MatchRow) Then
shtMaster.Rows(cell.Row).EntireRow.Copy Destination:=sht.Cells(MatchRow, 1)
Else
On Error GoTo SetFirst
lngLastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1
On Error GoTo 0
shtMaster.Rows(cell.Row).EntireRow.Copy Destination:=sht.Cells(lngLastRow, 1)
End If
If bolFound = False Then
For Each cmt In shtMaster.Comments
If cmt.Parent.Address = cell.Address Then cmt.Delete
Next cmt
cell.AddComment "no sheet found for this row"
ActiveSheet.EnableCalculation = False
ActiveSheet.EnableCalculation = True
End If
Set sht = Nothing
Next
End Sub
On Error GoTo SetFirst
This instruction tells the VBA runtime, in case of an error, to jump straight to the SetFirst subroutine to handle the error.
When you compile the code, VBA sees that there's a conditional jump to that SetFirst label, but there's no such label to jump to, so VBA can't resolve SetFirst and compilation fails.
Not sure what your intent is, but things would typically look something like this:
Exit Sub
SetFirst: '<<<<<<<< that's your line label
Debug.Print "Error " & Err.Number & ": " & Err.Description
Err.Clear
'comment-out or remove before distributing:
Stop
Resume 'step through (F8) here to jump back to error-causing instruction
End Sub
Line labels / subroutines are locally scoped, meaning you can't GoTo-jump to a line label that's located in another procedure. If you have SetFirst in another procedure and intend to jump there in case of an error, you have some serious spaghettification in process.

VBA (Upper) Type Mismatch Error

I am running a bit of VBA to switch an entire Excel worksheet to upper case.
However it trips over and gives a Type Mismatch error and fails half way through.
Sub MyUpperCase()
Application.ScreenUpdating = False
Dim cell As Range
For Each cell In Range("$A$1:" & Range("$A$1").SpecialCells(xlLastCell).Address)
If Len(cell) > 0 Then cell = UCase(cell)
Next cell
Application.ScreenUpdating = True
End Sub
I'm assuming it is tripping over a specific cell however there are hundreds of lines. Is there a way to get it to skip errors
If you want to convert all cells to upper case text (including formulas):
Sub MyUpperCase()
Application.ScreenUpdating = False
Dim cell As Range, v As String
For Each cell In Range("$A$1:" & Range("$A$1").SpecialCells(xlLastCell).Address)
v = cell.Text
If Len(v) > 0 Then cell.Value = UCase(v)
Next cell
Application.ScreenUpdating = True
End Sub
Be aware that all formulas not returning Null will also be converted to Text.
To see what cell (or cells) is the problem, you could try:
On Error Resume Next 'to enable in-line error-catching
For Each cell In Range("$A$1:" & Range("$A$1").SpecialCells(xlLastCell).Address)
If Len(cell) > 0 Then cell = UCase(cell)
If Err.Number > 0 Then
Debug.Print cell.Address
Err.Clear
End If
Next cell
On Error GoTo 0 'Turn off On Error Resume Next
On Error Resume Next is often abused, especially by new VBA programmers. Don't turn it on at the beginning of a sub and never turn it off and never check Err.Number. I find it a very good idea to think of it having a specific scope, and emphasizing that scope by indenting the statements in it, as I have done above. #MacroMan raises a good point that errors shouldn't be simply ignored (which is what happens if you abuse this construct).
Add the following error trapping in the middle of your code:
On Error Resume Next
If Len(cell) > 0 Then cell = UCase(cell)
If Err.Number <> 0 Then
MsgBox "Cell " & cell.Address & " has an error !"
End If
On Error GoTo 0
Note: Your code is fine with Numeric values, it's the #NA and #DIV/0 that's raising the errors when running your original code.

Unable to get worksheet the VLookup property of the WorksheetFunction Class error

Private Sub TextBox2_AfterUpdate() 'Badge Number
On Error GoTo Err
Dim tbl As ListObject, fndStr As String
Set tbl = Sheet9.ListObjects("EmployeeList")
fndStr = Trim(Me.TextBox2.Value)
MsgBox fndStr
If fndStr <> "" Then
Me.TextBox3.Value = Application.WorksheetFunction.VLookup(fndStr, tbl, 2, False) '<-- Error Line
End If
Exit Sub
Err:
MsgBox Err.Description
End Sub
I have a table named as "EmployeeList" and I am doing simple vlookup using Badge number but I am getting the error for unknown reason. I know there are similar questions asked before but I did read before posting this.
As you can clearly see the table name in the image and Entered value that is 10 for the first parameter on vlookup function but it doesn't returns any value but gives error. Don't know what's wrong.
'I tried this as well
Me.TextBox3.Value = Application.WorksheetFunction.VLookup(fndStr, Sheet9.Range("A1:F" & Rows.Count), 2, False) '<-- Error Line
'And this
Me.TextBox3.Value = Application.WorksheetFunction.VLookup(fndStr, Sheet9.Range("EmployeeList"), 2, False) '<-- Error Line
Also for unknown reason I can't do
Application.Vlookup as well
Like when I do Application.V
Vlookup doesn't shows up in the list.
There are two issues.
The first, you have tried to solve, is that you need a Range as Arg2in Vlookup. Since your tbl is a ListObject. you could simply use tbl.Range, see ListObject.Range Property.
The second is, that Vlookup will not find strings in a column of numbers. And your first column is a column of numbers. So you need to convert the string into number.
Me.TextBox3.Value = Application.WorksheetFunction.VLookup(CDbl(fndStr), tbl.Range, 2, False)
should work.
Please find the code below, i have used evaluate method to get vlookup result.
Private Sub TextBox2_AfterUpdate()
Dim fndStr As String
On Error GoTo Err_Desc
fndStr = Trim(Me.TextBox2.Value)
MsgBox fndStr
If fndStr <> "" Then
'// Using Eval method
Me.TextBox3.Value = Evaluate("=VLOOKUP(" & fndStr & ",EmployeeList[#All],2,0)")
End If
Exit Sub
Err_Desc:
MsgBox Err.Description
End Sub

VBA Match function to find ActiveCell Value on inactive sheet and change value on active sheet

I try to find the value of the Active cell where my cursor is using the application.match function on a different sheet. If it is found i want to change the value of a cell on my active sheet based on the ActiveCell.Row and a determined column.
I tried to use this code
Sub test()
Dim wert As String
Dim such1 As String
Dim var As Integer
such1 = ActiveCell.Value
On Error Resume Next
var = Application.Match(such1, Worksheets(Test1).Columns(1), 0)
If Err = 0 Then
wert = Sheets("Test2").Cell(var, "N").Value
Sheets("Test2").Cell(ActiveCell.Row, "O").Value = wert
Else
MsgBox "Value not existent"
End If
End Sub
Somehow i always get the error message. I dont understand why though. Do you have any idea?
Use syntax like this:
Option Explicit
Public Sub test()
Dim foundRow As Variant
Dim activeRow As Long
Dim foundN As String
activeRow = ActiveCell.Row
foundRow = Application.Match(ActiveCell, Worksheets("Test1").Columns(1), 0)
If Not IsError(foundRow) Then
foundN = Worksheets("Test2").Cells(foundRow, "N").Value
Worksheets("Test2").Cells(activeRow, "O").Value = foundN
Else
MsgBox "Value not existent"
End If
End Sub
Mistakes in your code:
Worksheets(test1) should be Worksheets("Test1")
Worksheets("Test2").Cell should be Worksheets("Test2").Cells ("s" at the end of Cells)
There are subtle differences between Application.Match() and WorksheetFunction.Match()
WorksheetFunction.Match() is not as reliable as Application.Match()
WorksheetFunction.Match() throws a run-time error
you need to use the statement On Error Resume Next to bypass the VBA error
Application.Match() returns an Error Object
the statement On Error Resume Next doesn't work
to check the return value you have to use If IsError(Application.Match(...))
Note how foundRow is defined: Dim foundRow AsVariant
The return value can be the row number (a Long) or an Error object (Variant)

Excel VBA "Method Range of object _worksheet failed

I am trying to do some VBA programming but running into a strange situation. The code below runs fine in one excel file but not another, the error in the title appears in the line where I assign SearchRange variable.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$B$3" Then
Dim rngX As Range
Dim counter As Integer
Dim wsLeit As Excel.Worksheet
Dim wsFilt As Excel.Worksheet
Dim searchValue As String
Dim searchRange As Range
Dim rownr As String
Set wsLeit = Excel.ThisWorkbook.Sheets("Leit")
Set wsFilt = Excel.ThisWorkbook.Sheets("FILT")
Set searchRange = wsFilt.Range("A4:ZZ10000")
searchValue = wsLeit.Range("B3").Value
Set rngX = searchRange.Find(what:=searchValue, lookat:=xlPart)
wsLeit.Range("A6:B200").ClearContents
If Not rngX Is Nothing Then
strFirstAddress = rngX.Address
counter = 8
rownr = Split(rngX.Address, "$")(2)
For Each c In wsFilt.Range("A" & rownr & ":" & "ZZ" & rownr)
If Not IsEmpty(c.Value) Then
wsLeit.Range("A" & CStr(counter)).Value = c.Value
foundColumn = Split(c.Address, "$")(1)
wsLeit.Range("B" & CStr(counter)).Value = wsFilt.Range(foundColumn & "1").Value & " " & wsFilt.Range(foundColumn & "2").Value
counter = counter + 1
End If
Next
Else
MsgBox "Fann ekkert"
End If
End If
End Sub
Any idea why this code works in one workbook but not another? (the sheets have the same name in both books)
EDIT1:
For completeness sake here is the full error:
Runtime Error '1004':
Method 'Range' of object '_Worksheet' failed
The problem was that pre-Excel 2007 versions have a smaller number of columns, and this sometimes creates random failures when the file format changes.
Some Excel 2003 specs:
Worksheet size 65,536 rows by 256 columns
Column width 255 characters
Row height 409 points
Page breaks 1000 horizontal and vertical
Excel 2010:
Worksheet size 1,048,576 rows by 16,384 columns
Column width 255 characters
Row height 409 points
Page breaks 1,026 horizontal and vertical
Total number of characters that a cell can contain 32,767 characters
A good practice to safeguard against this problem is to add a "guard" subroutine in the Workbook_Open event that checks (using Application.Version) if the current excel version is the minimum one for which the file is meant to be. You can store the minimum excel version in the Workbook.Names Collection as a constant and check against that constant.
I hope this helps!