Find and replace in specific Excel column - excel

How to modify this script to only find and replace in a specific column?
Set xl = CreateObject("Excel.Application")
xl.Visible = True
Set wb = xl.Workbooks.Open("C:\Users\test.xlsx")
Set ws = wb.Sheets("Sheet1")
Set objRange = ws.Range("Q1").End(xlDown).Select
objRange.Replace "~*", ""
The current script gives an error on the Set objRange line. Replacing * in the entire sheet would interefere with formulas.

You're thinking too complicated. Just tell the Range property that you want the entire Q column and call the Replace method directly on that Range object:
ws.Range("Q:Q").Replace "~*", ""

Related

Find values through multiple Excel files and write the whole row to a text file

I am currently trying to create an .vbs script file where you can find multiple values through multiple excel files and then (if results were found) write the entire row to an .txt file.
How to extract the value data of the entire row where the value has been found in string format in order to write it to the text file?
This is my progress so far:
sOutputPath = "C:\output.txt"
Set oExcel = CreateObject("Excel.Application")
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oOutputFile = oFSO.CreateTextFile(sOutputPath, True)
Dim aFiles() 'Array of excel file paths
Dim aSearch() 'Array of search values
fMain()
Sub fMain()
oExcel.visible = False
oExcel.DisplayAlerts = False
'Set search values (this is the way I prefer it for now, all strings)
aSearch(0) = "Test"
aSearch(1) = "1236xy"
'Set excel paths
aFiles(0) = "C:\workbook1.xlsx"
aFiles(1) = "C:\workbook2.xlsx"
aFiles(2) = "C:\workbook3.xlsx"
For Each file in aFiles
Set oWorkbook = oExcel.Workbooks.Open(file, , true) 'Open Read-Only
Set oWorksheet = oWorkbook.Worksheets(1) 'Always the first sheet
Set oRange = oWorksheet.UsedRange 'Search everywhere
For Each entry in aSearch
Set oTarget = oRange.Find(entry)
If Not oTarget Is Nothing Then
oOutputFile.WriteLine(file) 'Write the file path as a title if a value was found within that file
'Here I became stuck and don't know how to proceed, I need the write the whole row where the cell containing the value was found to the oOutputFile
End If
Next
On Error Resume Next
oWorkbook.Saved = True
oWorkbook.Close(False)
Next
oOutputFile.Close
oExcel.Quit
End Sub
wScript.Quit

VBScript to delete the row if particular column cell value is empty (based on Column name)

I am new to VBScript. I need little help on deleting the entire row in excel based on particular column value (trying to pass the column name as argument, Column name will be vary everytime). Based on the column name, script should check the cells and if any cell contains empty value then delete the entire row.
Any help would be appreciate.
Dim objExcel, objWorkbook, objSheet, objWorksheet
Const xlCellTypeBlanks = 4
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\Desktop\test.xlsx")
Set objWorksheet = objWorkbook.Sheets(1)
a = "LastName"
With Columns(a)
.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End With
This is my code but it is not working as expected
Use the worksheet's MATCH function through Excel.Application to get the ordinal position of the column by matching the column header label in row 1.
Dim objExcel, objWorkbook, objSheet, objWorksheet
Const xlCellTypeBlanks = 4
'Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\Desktop\test.xlsx")
Set objWorksheet = objWorkbook.Sheets(1)
a = "LastName"
With objWorksheet.Columns(objExcel.match(a, objWorksheet.rows(1), 0))
.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End With

Find value in Excel from Outlook

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

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

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