VBA - Range: "Run-time error '91' - excel

If the workbook isn't saved and closed and reopened,
I get the following error
"Run-time error '91': Object variable or With block not set"
I have the exact same code (only the name of the string is different) on other places, and sometimes it gives me the same error until I save close and reopen and re-run. Afterwards, the code runs smoothly.
Any ideas on how to avoid the bug? Have you had this problem before?
Dim fal As Excel.Worksheet
Set fal = wb.Sheets("Falancs")
Dim x As String
x = "F_1 ="
Dim cc As Integer ' The column as an integer (cc = 1,2,3...)
cc = fal.UsedRange.Find(x).Column
Error is on the last line, where the "(x)" is ...

.Find returns Nothing if value of x not found, so you should check it:
Dim fal As Excel.Worksheet
Set fal = wb.Sheets("Falancs")
Dim x As String
x = "F_1 ="
Dim cc As Integer ' The column as an integer (cc = 1,2,3...)
Dim res As Range
Set res = fal.UsedRange.Find(x)
If Not res Is Nothing Then
cc = res.Column
Else
MsgBox "Value " & x & " not found"
Exit Sub
End If

Related

Calling excel from solidworks works 1 time out of 2

This may sound a little bit dumb, but I have never experienced anything like this before with SolidWorks macro. I have written a SolidWorks macro that inserts a BOM table into an assembly saves it as excel, and adds needed formulas to an excel file. However it works 1 time out of 2- 1st time- all good, 2nd time I get an error- "Run-time error '1004' Method 'Rows' of object '_Global' Failed", 3rd time- all good, 4th time I get the same error and so on and so on. I'm really new to excel macro so I don't know if I'm missing something or just stupid?
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swBOMAnnotation As SldWorks.BomTableAnnotation
Dim i As Integer
Dim nNumRow As Variant
Dim swTableAnn As SldWorks.TableAnnotation
Dim swAnn As SldWorks.Annotation
Dim swModelDocExt As SldWorks.ModelDocExtension
Dim template As String
Dim fType As String
Dim configuration As String
'excel variables
Dim x1App As Excel.Application
Dim xlWB As Excel.Workbook
Dim NextRow As Long
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swModelDocExt = swModel.Extension
template = "C:\Program Files\SOLIDWORKS Corp\SOLIDWORKS\lang\english\bom-all.sldbomtbt"
fType = swBomType_PartsOnly
configuration = "Default"
Set swBOMAnnotation = swModelDocExt.InsertBomTable3(template, 770, 240, fType, configuration, False, 2, True)
Dim path As String
path = Left(swModel.GetPathName, InStrRev(swModel.GetPathName, "\"))
Dim fpath As String
fpath = Format(path & "BOM\")
On Error Resume Next
MkDir (fpath)
On Error GoTo 0
Dim fName As String
fName = Format(fpath & "TEST.xls")
swBOMAnnotation.SaveAsExcel fName, False, False
Set swTableAnn = swBOMAnnotation
Set swAnn = swTableAnn.GetAnnotation
swAnn.Select3 False, Nothing
swModel.EditDelete
'Excel part
Set x1App = New Excel.Application
x1App.Visible = True
Set xlWB = x1App.Workbooks.Open(fName)
With Range("G3:G" & Cells(Rows.Count, "C").End(xlUp).Row)
.Formula = "=C3*F3"
End With
NextRow = Range("G" & Rows.Count).End(xlUp).Row + 1
Range("G" & NextRow).Formula = "=SUM(G2:G" & NextRow - 1 & ")"
End Sub
Not sure what's causing the behavior you're describing but here are a few thoughts that might point you in the right direction.
Objects in macros are persistent, meaning swModel (and other objects) will still exist after the macro is run. This is why you need to set it to 'Nothing' before using it again.
"Rows" is not defined anywhere so I'm surprised that code works at all. It must be late binding it to something... Rows is a method for an excel range but you're not using it that way. (range.Rows)
Try getting the row count explicitly in a double and using that instead. I suspect that will fix your issue.

is there away how to handle error 13 in vba

Hello
I have an error 13 on my vlookup all the time ,when I execute vlookup on my sheet it works soon vba doesn't I am looking for help
here is my code , all the columns are Text in my sheet
Sub address_change()
Dim updatesheet As Variant
Dim sbw As String
Dim Param As String
Dim entier As Integer
Dim fname As String
Dim tsk As Task
Dim rg As Variant
Dim ws As Sheets
Dim wb As Excel.Workbook
Dim appXLS As Object
Dim entxls As Object
Dim i As Integer
Set appXLS = CreateObject("Excel.Application")
If appXLS Is Nothing Then
MsgBox ("XLS not installed")
End If
fname = ActiveProject.Path & "\" & Dir(ActiveProject.Path & "\addresses.xlsx")
MsgBox (fname)Set wb = appXLS.Workbooks.Open(fname, False)
Set rg = appXLS.Worksheets("sheet2").Range("A:U")
appXLS.Visible = TrueMsgBox (appXLS.Application.Value)
On Error Resume Next
For Each tsk In ActiveProject.Tasks
Param = tsk.Text2
If tsk.OutlineLevel = 2 Then
updatesheet = appXLS.Application.VLookup(Param, rg, 16, False)
If Err.Number <> 0 Then
tsk.Text13 = "No match 32"
Else
tsk.Text13 = updatesheet
End If
End If
Next tsk
End Sub
There are two ways to use the Excel VLookup (and similar functions like Match) with VBA, and they differ.
Application.VLookup (the version you are using) will return an error value Error 2042 if the search term cannot be found. This is not a runtime error, this is a return value. Error values are a special data type in VBA (they are not strings, the Error 2042 is just the representation of it). To be precise, this error is the #N/A that you see in Excel if a Vlookup fails.
You write the result into variable updatesheet, that is fine as it is declared as Variant, and a variant can hold an error value. However, now you check if an error occurred and as this is not the case, it will try to assign the error value to tsk.Text13 and this gives you a type mismatch error (I assume that tsk.Text13 expects a string).
Instead of checking for a runtime error as you do, you need to check if updatesheet contains an error value, this is done using the IsError-function. In this case, you could also use the Application.IsNA()-function.
The alternative is to use WorksheetFunction.Vlookup, this will throw a runtime error if can't find the search term, and you need to wrap this into Error handling.
Use either the one or the other method:
updatesheet = appXLS.VLookup(Param, rg, 16, False)
If appXLS.IsNA(updatesheet) Then
tsk.text13 = "No match 32"
Else
tsk.text13 = updatesheet
End If
updatesheet = "No match 32"
On Error Resume Next
updatesheet = appXLS.WorksheetFunction.VLookup(Param, rg, 16, False)
On Error GoTo 0
tsk.text13 = updatesheet
For further reading, I recommend https://rubberduckvba.wordpress.com/2021/02/15/worksheetfunction-and-errors/

Reading Date from Excel file in VBA Error Message

I have a function that gets the date from a certain cell in an excel sheet, splits the string that was in that cell using a space as a delimiter and keeps the first object in the array to store at as the date. However, I keep getting the following error message
"run-time error '91': Object variable or With block variable not set".
Any ideas of what might be wrong?
Public Function getDate(ws As Excel.Worksheet, row As Integer, col As Integer) As String
Dim inspDateTime As Variant
Dim dateArr() As String
Dim inspDateFinal As String
Set inspDateTime = ws.Cells(row, col)
dateArr = Split(inspDateTime, " ")
inspDateFinal = dateArr(0)
getDate = inspDateFinal
End Function
The following code is how I call the function:
Private Sub UploadData_Click()
Dim myWorkbook As Excel.Workbook
Dim myWorksheet As Excel.Worksheet
Dim inspDate As String
inspDate = getDate(myWorksheet, 10, 14)
' setting the workbook as the directory that was printed to the text box
Set myWorkbook = Workbooks.Open(Me.FilePathTxtBox)
' setting the first worksheet in the array of files entered
Set myWorksheet = myWorkbook.Worksheets(1)
End Sub

Run time Error 91 with HTML documents in excel VBA [duplicate]

I have the following code:
Sub AddSources()
Dim pubPage As Page
Dim pubShape As Shape
Dim hprlink As Hyperlink
Dim origAddress() As String
Dim exportFileName As String
exportFileName = "TestResume"
Dim linkSource As String
linkSource = "TestSource2"
Dim hyperLinkText As TextRange
For Each pubPage In ActiveDocument.Pages
For Each pubShape In pubPage.Shapes
If pubShape.Type = pbTextFrame Then
For Each hprlink In pubShape.TextFrame.TextRange.Hyperlinks
If InStr(hprlink.Address, "http://bleaney.ca") > 0 Then
hyperLinkText = hprlink.Range
origAddress = Split(hprlink.Address, "?source=")
hprlink.Address = origAddress(0) + "?source=" + linkSource
hprlink.Range = hyperLinkText
End If
Next hprlink
End If
Next pubShape
Next pubPage
ThisDocument.ExportAsFixedFormat pbFixedFormatTypePDF, "C:\" + exportFileName + ".pdf"
End Sub
I am getting the "Object variable or With block variable not set (Error 91)" error on the line with hyperLinkText = hprlink.Range. When I debug I can see that hprlink.Range does have a value. Any thoughts what I'm doing wrong?
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

Run-time error '-2147467261 (80004003) Object reference not set to an instance of an object

I'm getting the following error on the line 'ua' below. I'm trying to automate an Upsert to Salesforce through VBA using the enabler4excel object [automationObject].
Run-time error '-2147467261 (80004003)
Object reference not set to an instance of an object
Here is my code:
Dim addin As Office.COMAddIn
Dim automationObject As Object
For Each addin In Application.COMAddIns
If addin.Description = "Enabler for Excel" Then
Set automationObject = addin.Object
End If
Next addin
Dim error
result = automationObject.LogIn(Username,Password,"https://test.salesforce.com", error)
If result = False Then
MsgBox error
End
End If
Range("b1").Select
Selection.End(xlDown).Select
bot_acc = ActiveCell.Row
Dim ExternalId As String
ExternalId = Range("A1")
Dim ObjectName As String
ObjectName = "Account"
Dim AccUpArray(13, 9999) As Variant
For Column = 0 To 12
For Row = 0 To bot_acc - 2
AccUpArray(Column, Row) = Worksheets("Account").Range("A2").Offset(Row, Column)
Next Row
Next Column
ua = automationObject.UpsertData(AccUpArray, ObjectName, ExternalId, False, Nothing, error)
If Not error = Empty Then
MsgBox error
End
End If
I don't see where you dim ua but it is an object I assume (i.e. not an integer or string or boolean...) which means you need to use the keyword set
Set ua = automationObject.UpsertData(AccUpArray, ObjectName, ExternalId, False, Nothing, error)
Not seeing where you dim this could also mean you are not using Option Explicit. You should be.

Resources