Getting "subscript out of range" error from "Find" result - excel

I would like to find a string in an Excel worksheet. The Excel cell values are calculated using formulas. When I run this code:
Set firstExcel = CreateObject("Excel.application")
firstExcel.Workbooks.Open "C:\Myroute\excelName.xls"
Set oSht = firstExcel.Worksheets("Input Data")
str="hello"
Set aCell = oSht.Range("A1:E15").Find(str, , xlValues)
MsgBox aCell.row
I have an error that says:
Error: Subscript out of range
Code: 800A0009

The reason you get the error message on the .Find line is that vbscript does not recognize Excels constants, so you need to replace xlValues with the number -4163. (All Excel constant values can be found in the VBA Object Browser).
Also, the line you wrote Set oSht = firstExcel.Worksheets("Input Data") does not make sense to VB because firstExcel is the Excel Application itself and there is no Worksheet object associated with the Excel Application itself, but there is within the Workbook object.
Set firstExcel = CreateObject("Excel.application")
Set wkb = firstExcel.Workbooks.Open("C:\Myroute\excelName.xls")
Set oSht = wkb.Worksheets("Input Data")
str="hello"
Set aCell = oSht.Range("A1:E15").Find(str,,-4163)
If Not aCell is Nothing Then MsgBox aCell.row 'because if it does not find the string, it will not return a range object
Furthermore you could declare a constant at the top of your code and use that constant in the .Find statement.
const xlValues = -4163
.Find(str,,xlValues)

Related

Pull particular Excel cell value into Word document using Word VBA

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

How to graph a specified range with VBScript

I have an excel sheet with 5 columns in it. I want to use a VBScript to graph data only from columns A, D, and E.
Currently, using the code below, I am getting all 5 columns graphed. Please advise and thanks in advance.
With .ActiveChart
.SetSourceData(Source:=objXLSWorkSheet.Range("A:A" & LastRowofA, "D:D" & LastRowOfD, "E:E" & LastRowOfE))
End With
Try to use Union method to create the necessary range:
With .ActiveChart
.SetSourceData .Application.Union(objXLSWorkSheet.Range("A1:A" & LastRowofA), objXLSWorkSheet.Range("D1:D" & LastRowOfD), objXLSWorkSheet.Range("E1:E" & LastRowOfE))
End With
I used below code part to generate a chart with vbscript:
objWS = Objet worksheet ("Name"). objExcel = object Excel =>CreateObject("Excel.Application")
'Use this to select your specific range
With objWS
Set xlRange = objExcel.Union(.Range("B1:B5"), .Range("D1:D5"))
End With
With GetObject(, "Excel.Application")
'This code is using to SetSourceData with a specific range
objExcel.ActiveChart.SetSourceData xlRange
End With
'objWS = Objet worksheet ("Name"). objExcel = object Excel
=>CreateObject("Excel.Application")
'Use this to select your specific range
With objWS
Set xlRange = objExcel.Union(.Range("B1:B5"), .Range("D1:D5"))
End With

setting ranges using 'Set' in excel vba

Using this SO answer, i've been trying to get the following code to work.
' inserting formulas into the userOutput.csv sheet
Dim wsUser As Worksheet: Set wsUser = Worksheets("userOutput.csv")
Dim agentEmailRange As Range: 'Set agentEmailRange = wsUser.Range(Cells(2, agentEmailColumn), Cells(propertyRows, agentEmailColumn))
' following line fails with runtime error 1004, method 'range' of object '_Worksheet' fialed.
Set agentEmailRange = wsUser.Range(Cells(2, agentEmailColumn), Cells(propertyRows, agentEmailColumn))
wsUser.Range("I1") = "Agent Email"
With agentEmailRange
.Value = "VLOOKUP(RC[-1], 'agentsOutput.csv'!R2C1:R" & agentRows & "C6 ,4, FALSE)"
End With
the odd thing is it works one time. When I change one of the variables, however, it begins to fail.
How do I get that formula in the cells I need on a dynamic basis?
Try this one:
Dim wsUser As Worksheet
Dim agentEmailRange As Range
Set wsUser = Worksheets("userOutput.csv")
With wsUser
Set agentEmailRange = .Range(.Cells(2, agentEmailColumn), .Cells(propertyRows, agentEmailColumn))
.Range("I1") = "Agent Email"
End With
agentEmailRange.Formula = "=VLOOKUP(RC[-1], 'agentsOutput.csv'!R2C1:R" & agentRows & "C6 ,4, FALSE)"
You should fully qualify your Cells, i.e. specify to which sheet Cells belongs. Note that I'm using .Cells(..) instead Cells(..) - in that case Excel knows, that Cells belongs to sheet wsUser.

Access insert opened query in excel below existing data

Ok, so I have an Excel-file with data. This data comes from a query that has been manually copied from an Access database. Since this has to be done every day we want to make it automatically.
I already have VBA code inside the Access database that opens the query and writes it away into the Excel-file on the right sheet.
However, it works when I put a static range for the insert so it actually just overwrites the range I say:
Dim rst As DAO.Recordset
Dim ApXL As Object
Dim xlWBk As Object
Dim xlWSh As Object
Set rst = CurrentDb.OpenRecordset("Query name")
Set ApXL = CreateObject("Excel.Application")
ApXL.Application.ScreenUpdating = False
ApXL.Visible = True
Set xlWBk = ApXL.Workbooks.Open("C:\blabla.xlsm", True, False)
Set xlWSh = xlWBk.Worksheets(1)
xlWSh.Activate
xlWSh.range("A1341").CopyFromRecordset rst
xlWBk.Save
xlWBk.Close False
ApXL.Quit
rst.Close
Set rst = Nothing
Notice the xlWSh.range("A1341").CopyFromRecordset rst.
It just pastes the query from this row because I know this is the first empty row.
I already tried lots of other codes but I always get errors:
TheLastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
=> Error 424: Object required
Dim MyRange As range
Dim lngLastRow As Long
Set MyRange = xlWSh.range(strColum & "1")
lngLastRow = xlWSh.Cells(65536, MyRange.Column).End(xlUp).Row
=> Compilation-error on Dim MyRange As range: user-defined type not defined
Dim MyRange As Object
Dim lngLastRow As Long
Set MyRange = xlWSh.range(strColum & "1")
lngLastRow = xlWSh.Cells(65536, MyRange.Column).End(xlUp).Row
=> Error 1004: Application-defined or object-defined error
With xlWBk.Sheets("Sheetname")
lastrow = .range("A" & .Rows.Count).End(xlUp).Row
=> Error 1004: Application-defined or object-defined error
End With
With xlWSh
lastrow = .Cells.Find(What:="*", After:=.range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
=> Error 9: Subscript out of range
End With
So I have no idea anymore what to do.
The only other option is by reading the entire sheet into the Access database as a List or Array or Table and then do a .Count or something but inserting into lastRow+1 or firstEmptyRow should be quicker, doable and much easier to program.
Thanks in advance!
The problem is that Access doesn't know anything about Excel constants, such as xlUp, xlByRows and so on (until you add reference to excel library).
There are to ways for you:
1) Go to TOOLS->REFERENCES and add reference to Microsoft Excel 1x.0 Object Library (version may vary)
2) change all excel constants to their values (e.g. change SearchOrder:=xlByRows to SearchOrder:=1 and so on):
xlUp equals to -4162
xlByRows eqals to 1
xlPrevious eqals to 2
xlCellTypeLastCell equals to 11
Here is link with values of excel constants: xlConstants (or another way to determine constants values - is to use this line in EXCEL VBA : MsgBox xlCellTypeLastCell)

Excel Column delete using VBscript

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

Resources