Excel VBA "Method Range of object _worksheet failed - vba

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!

Related

How to get the count of the find results in vba

I have written a code to count the number of occurrence of the find results, the problem i am facing is., if the find data is more than 255 characters the code is returning count as '0' although we have some matches, where as for those find data which are less than 255 the code is properly working and fetching the right count.
Can anyone please rectify the issue, below is the code.
Sub CommentCount()
Dim CSAT_Comments As Workbook
Dim comment As Worksheet
Dim match As Worksheet
Dim CommentString As String
Dim MatchRow As Integer
Set CSAT_Comments = ActiveWorkbook
Set comment = CSAT_Comments.Worksheets("Qualitative Analysis_2018 Cycle")
Set match = CSAT_Comments.Worksheets("Consolidated Comments")
Dim CommentRange As Range
match.Range("A2").Select
Dim CRange As Range
Dim DuplicateCount As Integer
Set CommentRange = match.Range(Selection, Selection.End(xlDown)) 'Defining the range
For Each CRange In CommentRange.SpecialCells(xlCellTypeVisible)
CommentString = Left(CRange.Value, 255) 'Store the first 225 characters of the string
MatchRow = CRange.Row 'To get the row number of the respective comments
With comment
Application.ScreenUpdating = False
.Activate
Columns("AK:BL").Select 'Range which needs to be searched
DuplicateCount = Application.WorksheetFunction.CountIf(Range("AK:BL"), "" & CommentString) ' To get the count of find result and here is where i am getting the problem when the search string is >255
With match
.Activate
.Range("B" & MatchRow) = DuplicateCount 'Paste the count in the against respective commments
End With
End With
Next CRange
End Sub
use
CommentString = Left(CRange.Value, 254) & "*" 'Store the first 254 characters of the string, leaving the 255th character for final asterisk

How to set a different link in each cell in a range?

I'm programming a Macro in VB for Excel 2013 that search for coincidences in different worksheets, and add a link to the cells that match.
I'm havin torubles to insert the link in the cell, since the link must be different for a range of cells, I need help here.
Here is my code
Dim bufferDetails As String
Dim tmpCell As String
Dim spot As String
Dim cell As Variant
Dim cellSpots As Variant
For Each cell In Worksheets("MMS-Locations").Range("D2:D1833")
If (cell.Value2 = "NULL") Then
cell.Value2 = "NULL"
Else
tmpCell = cell.Text
'A62
If (Left(tmpCell, 3) = "A62") Then
spot = spotName(tmpCell)
For Each cellSpots In Worksheets("DetailedMap").Range("G60:CF123")
If (cellSpots.Value2 = spot) Then
For Each linkToSpot In Worksheets("MMS-Locations").Range("H2:H1833")
Worksheets("MMS-Locations").Hyperlinks.Add _
Anchor:=Range(linkToSpot), _
Address:="http://example.microsoft.com", _
ScreenTip:="Microsoft Web Site", _
TextToDisplay:="Microsoft"
Next linkToSpot
Debug.Print ("Encontrado " + cellSpots)
End If
Next cellSpots
End If
End If
Next cell
End Sub
Function spotName(fullName As String) As String
Dim realSpot As String
Dim lenght As Integer
lenght = Len(fullName) - 3
realSpot = Right(fullName, lenght)
spotName = realSpot
End Function
As I was thinking the linkToSpot variable contains the actual cell in the range, so I can move my selection of the sell, but my code fails in there with this error:
Error in the Range method of the '_Global' object,
Just for reference, here is what I use to convert a phone number to an email for texting..setting it as a hyperlink in the current cell.
ActiveCell.Value = myNumbr
Set myRange = ActiveCell
ActiveSheet.Hyperlinks.Add anchor:=myRange, Address:="mailto:" & myRange.Value, TextToDisplay:=myRange.Value`
Keep your code simple to start with, until you find a working script, then add other items. Make good use of the F8 key to step through your code to find out exactly where an error occurs.

Subtract two ranges and clear the contents from result

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.

formatting codes for footer not being applied and page orientation data mismatch

I have a worksheet(adHoc) where cell b28 contains
"&9 2014 YTD Financial Data for PP" & Chr(10) & " &D &T" & Chr(10) & " Version 1.0" & Chr(10) & " &F"
When I use the above to update the footer of another worksheet in a different workbook. I don't get the embedded formatting - it displays exactly what is contained in the cell b28.For example excel should see &9 and make the font 9 points.
I am also getting a datatype mismatch error with the page orientation. The contents of cell b36 is xlLandscape.
I posted a copy of this question last week on another board but did not get any answers. I hope someone here has answer.
http://www.mrexcel.com/forum/excel-questions/919033-updating-pagesetup-using-cells-master-worksheet-orientation-formatting-footer-excel-visual-basic-applications.html
This is the code I am using.
Sub page_setup()
Dim reportWB As Excel.Workbook
Dim sheet As Excel.Worksheet
'open report workbook - name of workbook is in cell b4
Set reportWB = Workbooks.Open(Workbooks("macros.xlsm").Sheets("adHoc").Range("b4").Value)
Dim leftFooter
leftFooter = Workbooks("macros.xlsm").Sheets("adHoc").Range("b28").Value
For Each sheet In reportWB.Sheets
With sheet
.PageSetup.leftFooter = leftFooter
.PageSetup.Orientation = Workbooks("macros.xlsm").Sheets("adHoc").Range("b36").Value
End With
Next
End Sub
Reading in your footer definitions like that they are treated as literal string, not code. You need to resolve the code to valid footer strings somehow.
For the LeftFooter string, you can use Evaluate to resolve it, but it will need to be written as if it's a Excel Formula, not VBA, so use
"&9 2014 YTD Financial Data for PP" & Char(10) & " &D &T" & Char(10) & " Version 1.0" & Char(10) & " &F"
Note the I use Char rather than Chr, the Excel formula equivalent.
For Orientation you are using a named constant, which won't work. Either put the value on your Excel sheet (2 in this case) or write your own code to resolve the name to its value
Working version (with corrected source data on sheet as descibed above)
Sub page_setup()
Dim reportWB As Excel.Workbook
Dim sheet As Excel.Worksheet
Dim wsSource As Worksheet
'open report workbook - name of workbook is in cell b4
Set wsSource = Workbooks("macros.xlsm").Sheets("adHoc")
Set reportWB = Workbooks.Open(wsSource.Range("b4").Value)
Dim leftFooter
leftFooter = wsSource.Range("b28").Value
For Each sheet In reportWB.Sheets
With sheet
.PageSetup.leftFooter = Evaluate(leftFooter)
.PageSetup.Orientation = wsSource.Range("b36").Value
End With
Next
End Sub
To handle the constants you could add a UDF that resolves the string names to values and call that from your settings sheet
Eg
Function GetConst(s As String) As Variant
Select Case s
Case "xlLandscape"
GetConst = xlLandscape
Case "xlPortrait"
GetConst = xlPortrait
' etc
End Select
End Function
Put in cell B36 GetConst("xlLandscape") (as a string, not formula), and change your Orientation line of code to
.PageSetup.Orientation = Evaluate(wsSource.Range("b36").Value)
Add any other named constants you want to the Select Case statement.
AFAIK, there is no (straightforward) way to do what you're trying to do. When you put code in a cell, and then call that cell's value in place of actual code, what VBA is trying to run is not:
.PageSetup.Orientation = xlLandscape
but rather:
.PageSetup.Orientation = "xlLandscape"
which will produce the errors and behavior you're seeing.
As rule of thumb, if your VBA code needs a string (ie, something in ""), or a number, you can do that calculation on the sheet and have the code pull in the value.
For everything else (there's Mastercard) put it in the code. For example:
leftfooter = cell1.value & Chr(10) & cell2.value & Chr(10) & cell3.value
(As a side note, I'm not familiar with the formatting it seems you're trying to do in that string... Those are generally set up through things like
With sheet.PageSetup.leftFooter.
.Font.Size = 9
'etc...
)

VBA: excel is closing, no error generated

I have a macro which I run on many file. The goal is to define a source and copy the value inside my file. It works fine for 30 source files but I recently have one that makes my excel crash, no error message nothing.
Here the code:
'dimensioning of the variables
'range and workbook
Dim Target_Area As Range
Dim Account_Number, Account_Description, Debit, Credit As Range
Dim General_Balance As Workbook
Dim Transform_file As Workbook
Dim Source_Range As Range
'technical var
Dim LastCell As Range
Dim LastCellNumber As Long
Dim Array_Position As Integer
Dim Worksheet_general_balance As Long
Dim Links As Variant
Dim address As String
'var used to adapt to the different trial balance
Dim startline, account_column, description_column, debit_column, credit_column As Integer
Dim column_to_test As String
Dim Target_Column(0 To 3) As Integer
'setting the variables
address = "blabla"
startline = 5
account_column = 1
description_column = 2
debit_column = 3
credit_column = 4
column_to_test = "A"
Target_Column(0) = 1
Target_Column(1) = 4
Target_Column(2) = 5
Target_Column(3) = 6
Worksheet_general_balance = 1
Set Transform_file = ActiveWorkbook
Set General_Balance = Workbooks.Open(address)
With General_Balance.Worksheets(Worksheet_general_balance)
Set LastCell = .Cells(.Rows.Count, column_to_test).End(xlUp)
LastCellNumber = LastCell.Row
End With
MsgBox "General TB sheet name: " & General_Balance.Worksheets(Worksheet_general_balance).Name
'3. save the required range from the source file
General_Balance.Worksheets(Worksheet_general_balance).Activate
Set Account_Number = General_Balance.Worksheets(Worksheet_general_balance).Range(Cells(startline, account_column), Cells(LastCellNumber, account_column))
Set Account_Description = General_Balance.Worksheets(Worksheet_general_balance).Range(Cells(startline, description_column), Cells(LastCellNumber, description_column))
Set Debit = General_Balance.Worksheets(Worksheet_general_balance).Range(Cells(startline, debit_column), Cells(LastCellNumber, debit_column))
Set Credit = General_Balance.Worksheets(Worksheet_general_balance).Range(Cells(startline, credit_column), Cells(LastCellNumber, credit_column))
'copying the value to the file
Transform_file.Activate
Transform_file.Worksheets("general balance").Range(Cells(6, Target_Column(0)), Cells(LastCellNumber - startline + 6, Target_Column(0))).Value = Account_Number.Value
Transform_file.Worksheets("general balance").Range(Cells(6, Target_Column(1)), Cells(LastCellNumber - startline + 6, Target_Column(1))).Value = Account_Description.Value
'up to this point, everything works well
'THE FOLLOWING TWO LINES EITHER ONE OF THEM MAKE EXCEL CRASH
Transform_file.Worksheets("general balance").Range(Cells(6, Target_Column(2)), Cells(LastCellNumber - startline + 6, Target_Column(2))).Value = Debit.Value
Transform_file.Worksheets("general balance").Range(Cells(6, Target_Column(3)), Cells(LastCellNumber - startline + 6, Target_Column(3))).Value = Credit.Value
General_Balance.Close
If I replace the range name Debit or Credit by Account_Number for example, the macro will finish, so i guess it's not about the destination.
I tried to put this code:
For Each cell In Debit.Cells
MsgBox cell.Value
Next cell
Before the problematic lines, and it goes through all the cells without any problems.
I can't find any reason why it's not working... any idea ?
First I think you should add some On Error to your code, including a
MsgBox Err.Description,,Err.Number.
My first guess is that you are trying to write to an already open/locked file.
Sub test()
On Error GoTo Hell
'Do lots of things
'...
Adios:
Exit Sub
Hell:
MsgBox Err.Description, vbCritical, "Error " & Err.Number
Resume Adios
Resume
End Sub
With the above sample, when you get the message box, press Ctrl+Break, move the yellow dot from the resume Adios to the Resume line, then press F8. Now you are on the line that caused the error.
Another way is to start your Sub in debug mode, and press F8 until it crashes (and remember where that was !).