I am having trouble performing an Excel vlookup from Outlook.
Here is what I am trying to accomplish:
- loop through each email in inbox
- if the subject line meets a criteria then get value
- go into excel and vlookup that value
- if the value exists, activate the cell and shift over to get the text value of the adjacent cell and bring it back to outlook to insert in an email (not there yet).
This is the code I'm stuck on (keep getting the 'object required' error):
Dim objExcel As Object
Set objExcel = CreateObject("Excel.Application")
.
Dim result As String
result = Right(subject, 7)
Dim found As Boolean 'can this be boolean?I just want to know if its exists or not
found = objExcel.WorksheetFunction.VLookup(result, Sheet1.Range("A:A"), 1, False)
I thought the objExcel would replace the 'Application' as that would default to Outlook.
I do want to mention, I have code that will open the excel file and loop through each email to get the subject line value successfully but I just cant seem to get control of it to perform functions.
Update - I tried this and it worked BUT the value was set to false when It should be true. Can you confirm this is correct?
Dim wrksht As Object
Set wrksht = objExcel.ActiveWorkbook.Sheets("Sheet1")
Dim res As Boolean
sourceWB.Activate
With objExcel
res = Not IsError(objExcel.Match(result, wrksht.Range("A:A"), 0))
End With
You can use Match if you just want to check if something exists.
Note: if you drop the WorksheetFunction then you can test the return value to see if it's an error: if you include WorksheetFunction then your code will generate a run-time error in the event there's no match.
Dim objExcel As Object, wb As Object, sht As Object
Dim result As String, found As Boolean
Set objExcel = CreateObject("Excel.Application")
'
'
Set wb = objExcel.Workbooks.Open("path_goes_here.xlsx")
Set sht = wb.Sheets(1) 'or use the sheet tab name
'
result = Right(subject, 7)
found = Not IsError(objExcel.Match(result, sht.Range("A:A"), 0))
EDIT: if you want a corresponding value from another column then you could do this -
Dim m, answer
result = Right(subject, 7)
m = objExcel.Match(result, sht.Range("A:A"), 0)
If Not IsError(m) Then
answer = sht.Cells(m, "B").Value
Else
answer = "Not found!"
End If
I decided to use the following:
For Each cell In objExcel.Range("A:A")
If CStr(cell) = result Then
.
.
.
thanks #TimWilliams for working with me on this!!
here is a full example
Sub vLookup()
Dim objExcel As Object
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Dim xlWB As Object
Set xlWB = objExcel.Workbooks.Add
Dim xlSheet As Object
Set xlSheet = xlWB.Sheets("Sheet1")
Dim formula As String
Dim result As String
xlSheet.Range("a3") = "abc123"
xlSheet.Range("a4") = "abc"
xlSheet.Range("a5") = "123"
Stop ' press F8 to single-step from here
result = "abc123" ' this will be found
formula = "IFNA(MATCH(""" & result & """,A:A,0),0)" ' cell formula: =IFNA(MATCH("abc123",A:A,0),0) return 0 if not found
Debug.Print objExcel.Evaluate(formula) ' returns 3 in this example
' press ctrl-G to see output of Debug.Print
result = "aaa" ' this will not be found
formula = "IFNA(MATCH(""" & result & """,A:A,0),0)" ' cell formula: =IFNA(MATCH("aaa",A:A,0),0) return 0 if not found
Debug.Print objExcel.Evaluate(formula) ' returns 0 in this example
Set xlSheet = Nothing
Set xlWB = Nothing
Set objExcel = Nothing
End Sub
Related
I am new to VBA and macros.
I got the repeated task of copy data from Excel and paste it in a particular location in the word document.
For example, my excel sheet has the data like this:
Col1
Col2
ID_1
I'm_One
ID_2
I'm_Two
ID_3
I'm_Three
Now i'm looking for a Word macro
Get text in Word table with cell position 3
Find the same text in Excel Col1
Get the value of Col2 from Excel
Paste the value of Col2 in word table with cell position 10
Repeat the same process for another table in Word document
[Update]
I have tried with multiple code snippets by google search but unable to construct the working macro.
Sub pull_from_Excel2()
'ref: https://www.macworld.com/article/211753/excelwordvisualbasic.html
Dim Month As String
ID_Range = "A2:A6" 'Select this as range like "A2:A16"
Offset_to_fetch = 1 'Select this to fetch comments etc. value starts with
Set xlSheet = GetObject("D:\Excel.xlsx")
'Snippets:
'Debug.Print VarType(xlSheet.Worksheets("Sheet1").Range("A3:A5").Value)
'8204
Dim Cell As Range, rng As Range
Debug.Print VarType(xlSheet.Worksheets("Sheet1").Range(ID_Range).Value2)
Set rng = xlSheet.Worksheets(1).Range(ID_Range)
For Each Cell In rng
Debug.Print Cell.Text
Next Cell
End Sub
I used this url to construct my skeleton code: https://www.macworld.com/article/211753/excelwordvisualbasic.html
When i try to get the values from the range of cells in excel, i got the following error for the code.
Set rng = xlSheet.Worksheets(1).Range(ID_Range).Value2
The above line gives "Object required" error when running.
Set rng = xlSheet.Worksheets(1).Range(ID_Range)
The above line gives "Type Mismatch" error when running.
Notes: For this error, I tried to use for each loop as this is array but the error is showing before executing the for loop.
Kindly assist.
I recommend to use Option Explicit and declare all your varibales properly. This way it is less likely that you end up with unseen errors.
To activate it for all new codes that you add in the future, you can activate it directly in Excel and Word. This is a good practice and will protect you from doing it wrong by notifying you of not declared variables:
In the VBA editor go to Tools › Options › Require Variable Declaration.
This will add Option Explicit to new modules only. In existing modules Option Explicit needs to be added manually as first line.
Further I highly recommend to name your variables according what they contain because otherwise it gets very confusing. You named your variable xlSheet but you load a workbook into it and not a worksheet.
The next issue is that your code is in Word and if you declare rng As Range then this is of type Word.Range and not Excel.Range and those are diffetent types so that is why you get a "Type Mismatch" error.
To solve this you either go in Word VBA to Extras › Refereces … and set a reference to the Excel library so you can declare your variable Dim xlRng As Excel.Range or if you don't set a reference you declare it as Object or Variant like in below example:
' This code is in Word!
Option Explicit
Public Sub pull_from_Excel2()
'declare constants
Const ID_Range As Sting = "A2:A6" 'Select this as range like "A2:A16"
Const Offset_to_fetch As Long = 1 'Select this to fetch comments etc. value starts with
Dim xlWorkbook As Object
Set xlWorkbook = GetObject("D:\Excel.xlsx") 'This expects the Excel to be already open! If not open you need to use CreateObject("Excel.Application")
Dim xlRng As Object
Set xlRng = xlWorkbook.Worksheets(1).Range(ID_Range)
Dim xlCell As Object
For Each xlCell In xlRng
Debug.Print xlCell.Text
Next xlCell
End Sub
Note if your workbook Set xlWorkbook = GetObject("D:\Excel.xlsx") is not open in Excel you need to use CreateObject("Excel.Application") and open it.
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
Dim xlWorkbook As Object
Set xlWorkbook = xlApp.Workbooks.Open(FileName:="D:\Excel.xlsx") 'will open the workbook
xlApp.Visible = True 'make it false to open Excel invisible in the background
'your code here …
'in the end close workbook and Excel (espaciall if you had it invisible!)
xlWorkbook.Close SaveChanges:=False
xlApp.Quit 'close Excel
Option Explicit
Sub UpdateTables()
Const XLSX = "D:\Excel.xlsx"
Dim xlApp, wb, ws
Dim rngSearch, rngFound
Dim iLastRow As Long, n As Integer
' open spreadsheet
'Set xlApp = New Excel.Application
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(XLSX, 1, 1)
Set ws = wb.Sheets(1)
iLastRow = ws.Cells(ws.Rows.Count, "A").End(-4162).Row 'xlUp
Set rngSearch = ws.Range("A2:A" & iLastRow)
' update tables
Dim doc As Document, tbl As Table, s As String
Set doc = ThisDocument
For Each tbl In doc.Tables
s = tbl.Cell(1, 1).Range.Text
s = Left(s, Len(s) - 2)
Set rngFound = rngSearch.Find(s, LookIn:=-4163, LookAt:=1) ' xlValues, xlWhole
If rngFound Is Nothing Then
MsgBox "'" & s & "' not found in table " & tbl.Title, vbExclamation
Else
tbl.Range.Cells(3).Range.Text = rngFound.Offset(0, 1)
n = n + 1
End If
Next
wb.Close False
xlApp.Quit
MsgBox n & " tables updated", vbInformation
End Sub
The project is to reuse text previously written in reports where applicable for use in similar situations for future reports. They will of course have to be edited in detail.
The immediate challenge is to use a conditional combobox in ms_word vba to get data from ms-excel, lookup in one column, return response in next column.
The code below comes from:shorturl.at/rwMW3 It crashes at the first Set statement. Compile error: Syntax error.
This is the only code I have found for this application.
It crashes at the first Set statement. Compile error: Syntax error. Any help appreciated. I have of course entered the actual full path and sheet name.
Sub FillCCLsitWithExcelData()
Dim xlapp As Object
Dim xlbook As Object
Dim xlsheet As Object
Dim i As Long
Dim subject As String
Dim bStart As Boolean
Dim ffield As FormField
Dim oCC As ContentControl
On Error Resume Next
Set xlapp = GetObject(, "Excel.Application")
If Err Then bStart = True
Set xlapp = CreateObject("Excel.Application")
End If
On Error GoTo 0
Set xlbook = xlapp.Workbooks.Open("D:\Data Stores\Data Source.xlsx")
Set xlsheet = xlbook.Worksheets(1)
With xlsheet.Range("A1")
Set oCC =
ActiveDocument.SelectContentControlsByTitle("Names").Item(1)
For i = 2 To .CurrentRegion.Rows.Count
Debug.Print .Offset(i - 1, 0)
oCC.DropdownListEntries.Add Text:=.Offset(i - 1, 0),
Value:=.Offset(i - 1, 0)
Next i
End With
xlbook.Close
If bStart = True Then xlapp.Quit
End If
End Sub
I am writing a macro in CATIA v5 using VBA. The program is suppose to take points from a geometric set and transfer them into an excel file. I have successfully gotten the excel document open, a header created, but then I receive "Run-time error '438': Object doesn't support this property or method.
I have tried searching around and it seems like the section of code is trying to interact with something outside of its domain, but I cannot figure out how. Below is a sample of my code. The line that contains "***" to the left is the line that is being pointed out in the debugger.
Dim xls As Object
Dim wkbks As Object
Dim wkbk As Object
Dim wksheets As Object
Dim sheet As Object
Dim fs, f, f1, fc, s
Dim coords(2) As Integer
Dim PartDoc
Sub CATMain()
CATIA.ActiveDocument.Selection.Search "CATGmoSearch.Point,all"
'Function Calls
AppStart
CATIAtoXLS
'wksheet.Application.ActiveWorkbook.SaveAs (ExcelFolder & Left(CATIA.ActiveDocument.Name,Len(CATIA.ActiveDocument.Name)-8)&".xls")
'wksheet.Application.ActiveWorkbook.Close
End Sub
Private Sub AppStart()
Err.Clear
On Error Resume Next
Set xls = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Err.Clear
Set xls = CreateObject("Excel.Application")
End If
xls.Application.Visible = True
Set wkbks = xls.Application.Workbooks
Set wkbk = wkbks.Add
Set wksheets = wkbk.Worksheets(1)
Set sheet = wkbk.Sheets(1)
sheet.Cells(1, "A") = "X-Cord"
sheet.Cells(1, "B") = "Y-Cord"
sheet.Cells(1, "C") = "Z-Cord"
End Sub
Private Sub CATIAtoXLS()
For i = 1 To CATIA.ActiveDocument.Selection.Count
Set Selection = CATIA.ActiveDocument.Selection ***
Set Element = Selection.Item(i)
'Transfer data to xls
Point.GetCoordinates (coords)
sheet.Cells(i + 1, "A") = coords(0)
sheet.Cells(i + 1, "B") = coords(1)
sheet.Cells(i + 1, "C") = coords(2)
Next i
End Sub
Your first issue is that in any method in CATIA VBA which passes an array as an argument, must be called on a object declared variant (explicitly or by default).
So you it should look like this:
Dim px as Variant
Set px = CATIA.ActiveDocument.Selection.Item(i).Value
Call Point.GetCoordinates(coords)
The second problem is that in VBA if you use a subroutine with parentheses, you must use the Call keyword:
Call Point.GetCoordinates (coords)
Otherwise, you can skip the parentheses and the keyword:
Point.GetCoordinates coords
Created a simple access DB with only 1 form and 1 one button to run code that opens an existing empty excel (with 1 worksheet) and writes "X" in its 1st cell. It does the job but the workbook is hidden and I have to manually unhide it. That is, after the VBA code is executed I open the excel file and it is all grayed out. I have to click the "view" tab and then select the "Unhide" option and all is fine and I can see that the cell was updated as needed. If I take out the VBA line that writes "X" in the excel file, it doesn't hide the workbook. How do I solve the problem of the workbook being hidden?
Windows 7 and Office2013.
Thank you!!!
Here is the code:
Private Sub Command0_Click()
Dim my_xl_app As Object
Dim my_xl_worksheet As Object
Dim my_xl_workbook As Object
Set my_xl_app = CreateObject("Excel.Application")
my_xl_app.UserControl = True
my_xl_app.Visible = False ' yes. I know it's the default
Set my_xl_workbook = GetObject("D:\Dropbox\MASAV\HIYUVIM\AAA.xlsx")
Set my_xl_worksheet = my_xl_workbook.Worksheets(1)
my_xl_worksheet.Cells(1, "A") = "V"
my_xl_workbook.Close SaveChanges:=True
Set my_xl_app = Nothing
Set my_xl_workbook = Nothing
Set my_xl_worksheet = Nothing
End Sub
S o l v e d !!!
Here is the code that works without hiding my entire workbook :
Private Sub Command0_Click()
Dim my_xl_app As Object
Dim my_xl_worksheet As Object
Dim my_xl_workbook As Object
Set my_xl_app = CreateObject("Excel.Application")
Set my_xl_workbook = my_xl_app.Workbooks.Open("D:\Dropbox\MASAV\HIYUVIM\AAA.xlsx")
Set my_xl_worksheet = my_xl_workbook.Worksheets(1)
my_xl_workbook.Sheets(1).Range("A1").Value = "V"
my_xl_workbook.Close SaveChanges:=True
Set my_xl_app = Nothing
End Sub
Got the answer right here in this this forum, in another thread which escaped my eyes...
Thanks a lot to all in this wonderful forum!!!!
Use this:
Workbooks(1).Windows(1).Visible = True
I wrote a code in vbscript as below ,but when i run my script it is giving an error saying the "Range" is undefined. Can any help me here by saying what is the error?
For TaskCounter = 1 to 35
TaskRangeFrom="Task"&TaskCounter&" Start Date"
TaskRangeTo="Task"&(TaskCounter+1)&" Name"
objSheet6.Range(Range(TaskRangeFrom).Offset(,1), _
Range(TaskRangeTo).Offset(,-1)).EntireColumn.Delete
Next
Thanks in advance.
As #NickSlash mentioned yesterday, I doubt that you have given range names like
"Business Process ID" (containg spaces) to your columns. But as this may be
a version thing, I show you how to get a 'whole column' range object for a
column named "TaskB" (via the "define name" dialog):
' Range by Name
Set oRng = oWs.Range("TaskB")
To get a range for the second column by (column) number, use:
' Range by Number
Set oRng = oWs.Cells(1, 2).EntireColumn
Please note: row and column numbers start with 1. So your ".Offset(,1)"
code looks very fishy; it may have caused the "Unknown runtime error".
If you - as I suppose - wrote your column titles in the first row, you'll
have to loop over the columns of that row and check the values:
' Range by Lookup
Set oRng = Nothing
For nCol = 1 To 5
If "Title B" = oWs.Cells(1, nCol).Value Then
Set oRng = oWs.Cells(1, nCol).EntireColumn
Exit For
End If
Next
If you want to experiment, insert those snippets into test code like:
Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")
Dim sDir : sDir = oFS.GetAbsolutePathname("..\xls")
Dim sFSpec : sFSpec = oFS.BuildPath(sDir, "work.xls")
' Start clean
oFS.CopyFile oFS.BuildPath(sDir, "13763603.xls"), sFSpec
' Open .XLS
Dim oXls : Set oXls = CreateObject("Excel.Application")
Dim oWb : Set oWb = oXls.Workbooks.Open(sFSpec)
Dim oWs : Set oWs = oWb.Worksheets(1)
Dim oRng, nCol
' Range by XXX
...
oXls.Visible = True
WScript.Stdin.ReadLine
If Not oRng Is Nothing Then
oRng.Delete
WScript.Stdin.ReadLine
End If
oXls.Visible = False
oWb.Close False
oXls.Quit
Pics to give evidence:
To delete an entire column in VBScript simply do the following; This will delete the entire column A
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open _
("C:\myworkbook.xlsx")
objExcel.Visible = True
objWorkbook.Worksheets("Sheet1").Range("A:A").Delete
In VBA (macro's) just call the code below. This will delete the A column on the active sheet.
Range("A:A").Delete
Having seeing some complications in VBScript compared to VBA I would suggest the following rather-lazy method.
The easiest way to do anything VBScript-related in most office apps, Excel being one of them, is to start recording a macro, do what you wish manually, and then read the VBA that is generated and convert that VBA to VBScript.
Anyway here's some code to help you. Delete column E.
Const xltoLeft = -4131
StrName as string
StrName = "myfield"
Set NewWorkBook = objExcel.workbooks.add()
With objExcel
.Sheets("Sheet1").Select '-- select is a very bad practice, I'll update it later
'-- run your for loop
'for i= blah blah
If range.offset(0,i) = StrName then
Range.offset(0,i).Entirecolumn.delete xltoLeft
Msgbox "magical deletion"
Exit for
End if
'next i
End With
Reference : DELETE EXCEL COLUMN IN VBSCRIPT