VBA macro runs on one computer but not on the other - vba

I have a macro that runs fine on my computer, but when I put this macro on another computer it does not even allow to run in debug mode. It just crashes the MS Project saying that it stopped working.
Edit:
The crash comes from the following Set. I have already tried early binding as well Dim xlApp as Excel.Application but crashes anyway.
Dim xlApp As Object
Set xlApp = New Excel.Application
is there another way to set the xlApp as an Excel object?

Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
Try late binding the Excel object and remove the reference.

I'd suggest using Late Binding. As #Josh said - you'll need to remove your library references and update a substantial portion of your code.
Any constants that are specific to Excel will need updating to their numerical equivalent.
For example, when using PasteSpecial you'd use something like xlPasteValues.
Open the immediate window in Excel and enter ?xlPasteValues. This will return -4163 which is the number you must enter into your code in place of xlPasteValues.
Sub Test()
Dim oXL As Object
Dim oWrkBk As Object
Dim oWrkSht As Object
Set oXL = CreateXL
Set oWrkBk = oXL.Workbooks.Open("C:\Workbook1.xlsx")
Set oWrkSht = oWrkBk.worksheets("Sheet1")
With oWrkSht
.Range("A1").Copy
.Range("B1").PasteSpecial -4163 'xlPasteValues
End With
End Sub
Public Function CreateXL(Optional bVisible As Boolean = True) As Object
Dim oTmpXL As Object
'''''''''''''''''''''''''''''''''''''''''''''''''''''
'Defer error trapping in case Excel is not running. '
'''''''''''''''''''''''''''''''''''''''''''''''''''''
On Error Resume Next
Set oTmpXL = GetObject(, "Excel.Application")
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
'If an error occurs then create an instance of Excel. '
'Reinstate error handling. '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
If Err.Number <> 0 Then
Err.Clear
On Error GoTo ERROR_HANDLER
Set oTmpXL = CreateObject("Excel.Application")
End If
oTmpXL.Visible = bVisible
Set CreateXL = oTmpXL
On Error GoTo 0
Exit Function
ERROR_HANDLER:
Select Case Err.Number
Case Else
MsgBox "Error " & Err.Number & vbCr & _
" (" & Err.Description & ") in procedure CreateXL."
Err.Clear
End Select
End Function

please try this, just to see if it also crashes.
it creates the word object, then excel object and exits. each time it creates the object, it dispays the object name.
i am assuming that you also have msword installed
note: if you ever copy code from a web page, make sure that the quotation marks are correct. there appear to be several versions of quotation marks (opening quotes, closing quotes), and these are not valid in VBA
Sub test()
Dim myApp As Object
Set myApp = CreateObject("Word.Application")
MsgBox myApp.Name
Set myApp = CreateObject("Excel.Application")
MsgBox myApp.Name
Set myApp = Nothing
End Sub

Related

User-defined type not defined on Word to Excel function

A nice user has supplied me with a better solution to my already existing code but does not work within Word. I'm trying to open an excel document when a user clicks a button. There are multiple buttons that open the same document but I want it to change the worksheet if the document is already opened and not another instance of the document. The following gives me the error:
User-defined type not defined
Option Explicit
Public objExcel As Object
Sub Main()
On Error Resume Next
Set objExcel = GetObject(, "Excel.Application")
On Error GoTo 0
If objExcel Is Nothing Then
Set objExcel = CreateObject("Excel.Application")
End If
End Sub
'==================================================================
Public Sub QE1_Click()
Dim wb As Workbook
Dim sht As Worksheet
If objExcel Is Nothing Then
Main
End If
objExcel.Visible = True
Set wb = objExcel.Workbooks.Open("H:\My Documents\Flowchart to Word\Quality and Environmental management system flowchart.xlsm")
On Error Resume Next
Set sht = wb.Worksheets("Project enquiry")
On Error GoTo 0
If sht Is Nothing Then
MsgBox "Workbook doesn't have a sheet named 'Project enquiry'", vbCritical, "Sheet critical error"
Else
sht.Activate
End If
End Sub
Unsure on why this does not work
In general, Workbook and Worksheet are unknown objects for Word. Thus, you have to define them with Excel. like this:
Dim wb As Excel.Workbook
Dim sht As Excel.Worksheet
In general, wb As Workbook works pretty well, when the VBA code is in Excel, because then Excel is the default environment. But in Word, you have to specify it explicitly. Make sure that you add Microsoft Excel 1N.0 Object Library from VBEditor> Extras> Libraries:
If you want to make it a bit easier, define wb and sht as Object. This is called "late binding" and is a bit slower.

VBA Automatically add autocorrection entries in word from an excel list

I am trying to add a huge amount of autocorrect entries into WORD loading the data of an excel file/sheet.
This is actually not with Autocorrections purposes but in order to use shortcuts to introduce complete paragraphs to write much faster.
First I tried:
Sub autocorrectlist()
'TRYING OUT IF using variables works for a new autocorrect entry.
Dim myString1 As String
Dim myString2 As String
myString1 = "BBBB"
myString2 = "BBBB works works works"
AutoCorrect.Entries.Add Name:=myString1, Value:=myString2
This worked. when writing BBBB in Word get substitute by the other expression.
lets try to read values from the excel file.
It is a big long here the code but it consist basically in open an excel file and read the entries of an excel sheet, one column being the entries for the so called shortcut (the text that has to be substitute) and the other one the substituting text)
'lets create a huge list of modifiers
Dim i As Integer 'counter
'Read Excel File Megaclause
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.range
Dim ExcelWasNotRunning As Boolean
Dim WorkbookToWorkOn As String
'specify the workbook to work on
WorkbookToWorkOn = "C:\Users\JF30443\Desktop\WORK\EXCEL\megaclause7.xlsm"
'If Excel is running, get a handle on it; otherwise start a new instance of Excel
On Error Resume Next
Set oXL = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set oXL = New Excel.Application
End If
On Error GoTo Err_Handler
oXL.Visible = True
'Open the workbook
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn)
'Process each of the spreadsheets in the workbook
Dim mySht As Worksheet
Set mySht = oWB.Worksheets("sc6")
Dim lastRow As Integer
lastRow = mySht.Cells(mySht.Rows.Count, "A").End(xlUp).Row
Dim myName As String
Dim myAuto As String
'reading the values from the sheet
For i = 1 To lastRow
myName = mySht.Cells(i, 1).Value
myAuto = mySht.Cells(i, 2).Value
If myName <> "" And myAuto <> "" Then
MsgBox ("nr:" & i & "myName:" & myName & "//myauto:" & myAuto)
'note here: actually it read correctly the two first values of the SC6 sheet
'Since the values displayed by the msgbox are correct
'the following line gives an error
Application.AutoCorrect.Entries.Add Name:=myName, Value:=myAuto
'the error being:
'AutoCorrect cannot replace text which contains a space character.
End If
Next
If ExcelWasNotRunning Then
oXL.Quit
End If
'Make sure you release object references.
Set oRng = Nothing
Set oSheet = Nothing
Set oWB = Nothing
Set oXL = Nothing
'quit
Exit Sub
Err_Handler:
MsgBox WorkbookToWorkOn & " caused a problem. " & Err.Description, vbCritical, _
"Error: " & Err.Number
If ExcelWasNotRunning Then
oXL.Quit
End If
End Sub
As stated in the code between lines the code reads the sheet because the msgbox displays correctly the two first values of the sheet called "SC3" but inmediatly after it gives error.
I copied partially this code from internet, but the one I thought would be the most difficult part (reading from word in excel) works, and then I can not add the entry.
What is even more strange is that the first part of the code above pasted (the one with "BBBB") works, which is basically the same approach as in the loop.
I searched for info in the net but I did not find anything relevant relating to taht error.
Help is welcome
Thanks.
The problem was an initial space in the names of the sheet

VBA Outlook/Excel

I am writing a vba sub in outlook that will: grab a unique value from the mail, look for that value in the column of an excel file, and return an associated value. I am working with an the .find function from the excel library to lookup my unique value in the excel, however, find is supposed to return a range of the first occurrence of my value but I cannot assign that value to the variable: pointer. I cannot reference it. Any insights appreciated. thank you!
Sub OTM1S() '(ByVal Item As Object)
Dim xlApp As Object
Dim wb As Workbook
Dim pointer As Range
Set xlApp = CreateObject("Excel.Application")
Set wb = xlApp.Workbooks.Open("I:\referencefile.xlsx")
'On Error Resume Next
pointer = wb.Sheets("Bonds").Range("A1:A10000").Find("XS1058142081")
MsgBox pointer.Offset(0, 1)
'On Error GoTo 0
wb.Save
wb.Close
End Sub
Where you are trying to set an object reference you need the Set keyword. Try this:
Sub OTM1S() '(ByVal Item As Object)
Dim xlApp As Object
Dim wb As Workbook
Dim pointer As Range
Set xlApp = CreateObject("Excel.Application")
Set wb = xlApp.Workbooks.Open("I:\referencefile.xlsx")
'On Error Resume Next
Set pointer = wb.Sheets("Bonds").Range("A1:A10000").Find("XS1058142081")
MsgBox pointer.Offset(0, 1)
'On Error GoTo 0
wb.Save
wb.Close
End Sub
You should also handle the scenario where the reference is not found. This can be done like so:
Set pointer = wb.Sheets("Bonds").Range("A1:A10000").Find("XS1058142081")
If Not pointer Is Nothing Then
MsgBox pointer.Offset(0,1)
Else
MsgBox "Sorry, couldn't find that in the specified range."
End If

Calling VBA macro from .vbs file throws 800A03EC error

I'm trying to run a VBA macro through .VBS file(File name: Check_final.vbs). Here is the code
Option Explicit
run_macro
Sub run_macro()
Dim xl1
Dim sCurPath
Dim xlBook
Dim FolderFromPath
Set xl1 = CreateObject("Excel.application")
sCurPath =Wscript.ScriptFullName
Set xlBook = xl1.Workbooks.Open(sCurPath, 0, True)
xl1.DisplayAlerts = False
FolderFromPath = Left(sCurPath, InStrRev(sCurPath, "\"))
xl1.Application.run FolderFromPath & "Changed_chk.xlsm!Check"
Set xlBook = Nothing
End Sub
When I run this .vbs file I get this popup 'Changed_chk.xlsm is locked for editing' with Read only and notify options. If I acknowledge it with either Read only or notify option a excel sheet is opened in the name of Check_final (which is the file name of that .vbs file) and the above mentioned code is shown written in that excel file. Then I get a Windows script host error(code: 800A03AC) saying macro may not be available or all macro's are disabled.(Though I have enabled the macro as mentioned here.[http://www.addictivetips.com/windows-tips/enable-all-macros-in-excel-2010/)].
Any help on this is much appreciated. Thanks in advance.
You open your vbs-file instead of your excel-file... Also make sure that your function/sub is public. In the example below, I created a Public Sub Check in the module "YourModuleName", which I call from the vbs-file.
Option Explicit
run_macro
Sub run_macro()
Dim xl1
Dim xlBook
Dim FolderFromPath
Set xl1 = CreateObject("Excel.application")
FolderFromPath = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
set xlBook = xl1.Workbooks.Open(FolderFromPath & "Changed_chk.xlsm")
xl1.Application.run "'" & xlBook.Name & "'!YourModuleName.Check"
xl1.Application.Quit
End Sub
Try this simple code (UNTESTED)
Dim oXlApp, oXLWb, sCurPath
Set oXlApp = CreateObject("Excel.application")
sCurPath = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
Set oXLWb = oXlApp.Workbooks.Open(sCurPath & "Changed_chk.xlsm")
oXlApp.DisplayAlerts = False
oXlApp.Run "Check"
'~~> Close the file here. Save or discard the changes as per your requirement
'oXLWb.Close (True)
'oXLWb.Close (False)
oXLWb.Close
oXlApp.Quit
Set oXLWb = Nothing
Set oXlApp = Nothing
Also where is your macro? In a sheet or in a module? You may want to see THIS
I think there may be something wrong with calling the run_macro statement. From the test i created in excel VBA there is an error if i try to call the sub outside of another sub
Option Explicit
test
Sub test()
MsgBox ("Test")
End Sub
I think you may want to
Option Explicit
Sub Start
run_macro
End Sub
Sub run_macro()
'code here
End Sub
or remove the run_macro line altogether?

Workbooks.Open returns different file than Filename

I am having the strangest problem. I was writing the below code on my laptop the other day and it worked fine. Now, I am testing it on my desktop and it's stopped working.
First, here's my code
Dim oApp As Application
Dim oWb As Workbook
Set oApp = New Application
oApp.Visible = True
Set oWb = oApp.Workbooks.Open(Filename:="C:\myFile.xlsx", ReadOnly:=True)
debug.print oWb.name
'returns "SOLVER.XLAM"
' "SOLVER.XLAM" is not "myFile.xlsx'
debug.print oApp.Workbooks.Count
'returns 1
debug.print oApp.Workbooks(1).name
'returns "myFile.xlsx"
Now, I know that solver is an add in, and it gets loaded in the new application upon creating it... but how does it perform this switcheroo? I can still get to the correct file, but I don't want to risk it on the coincidence that there is only 1 file in my Application object (or that the first file is the one I loaded)
Additional Info
I am calling executing this macro from within an excel instance and I wish to open a separate excel instance and then open particular workbook ("C:\myFile.xlsx") inside that other instance.
The key problem I'm having is that when I open the other instance and then add the workbook and set it to my oWb variable... somehow, when I later call that oWb variable it refers to something different from what I had set it to.
'This is how it makes me feel:
Dim x As Integer
x = 5
Debug.Print x
' 12
I think if you just refine your code a bit to ensure you are doing exactly what you want, you will be fine. Since it's unclear whether you are calling the code from within Excel or another MS Office Application, I placed to subs below.
Run this if running it in Excel:
Option Explicit
Sub insideXL()
Dim oWb As Workbook
Set oWb = Workbooks.Open("C:\myFile.xlsx", ReadOnly:=True)
Debug.Print oWb.Name
Debug.Print Workbooks.Count
Debug.Print Workbooks(1).Name
oWb.Close false
Set oWb = Nothing
End Sub
Run this if running in another program. I use early binding, but you could use late binding as well, if you wish:
Sub outsideXL()
'make sure Microsoft Excel X.X Object Library is checked in Tools > References
Dim oApp As Excel.Application
Set oApp = New Excel.Application
Dim oWb As Excel.Workbook
Set oWb = oApp.Workbooks.Open("C:\myFile.xlsx", ReadOnly:=True)
oApp.Visible = True
Debug.Print oWb.Name
Debug.Print Workbooks.Count
Debug.Print Workbooks(1).Name
oWb.Close = True
Set oWb = Nothing
Set oApp = Nothing
End Sub
I found that this (which worked in 2007):
wb = excel.Workbooks.Open(filename, False, True)
needs to be written
excel.Workbooks.Open(filename, False, True)
wb = excel.ActiveWorkbook
for 2010