Find specific data in excel sheet using vb.net - vb.net

I have been trying to find a specific data in Excel through a WinForm application and then try to fetch the next value in the same row using vb.net.
Example:
ElementName Value
Age 24
Name John Clan
Music Rock
Suppose if I want to find Age. then I want to make the code return as 24 searching it from Excel file.
I tried pulling the whole Excel data into a Dataset but it wasn't helpful.
Kindly guide me.

Imports Interop = Microsoft.Office.Interop.Excel
'Find In Excel
Private Function FindValueInExcel(ByVal sTextToFind)
Dim currentFind As Interop.Range = Nothing
Dim firstFind As Interop.Range = Nothing
Dim xlappFirstFile As Interop.Application = Nothing
Dim sSearchedValue As String
xlappFirstFile = CreateObject("Excel.Application")
xlappFirstFile.Workbooks.Open("D:\Sample.xlsx")
Dim rngSearchValue As Interop.Range = xlappFirstFile.Range("A1", "C5")
currentFind = rngSearchValue.Find(sTextToFind, , _
Interop.XlFindLookIn.xlValues, Interop.XlLookAt.xlPart, _
Interop.XlSearchOrder.xlByRows, Interop.XlSearchDirection.xlNext, False)
If Not currentFind Is Nothing Then
sSearchedValue = DirectCast(DirectCast(currentFind.EntireRow, Microsoft.Office.Interop.Excel.Range).Value2, System.Object)(1, 3).ToString()
Else
sSearchedValue = ""
End If
Return sSearchedValue
End Function
Link which helped me - http://msdn.microsoft.com/en-us/library/e4x1k99a.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

Related

Loop using Vlookup application in VBA is causing Excel to Not respond

I'm using three Workbooks. My Current workbook, The database workbook (DB_Wkb), the Document to change ( Doc_Wkb) and my current macro file.
I'm using vLookup to compare the ID, and get the name from the database The problem is that it works fine, but it takes a lot of time and Excel stops responding. I believe the use of vlookup is what makes my macro to take so long.
Dim Doc_Wkb As Workbook 'Document
Dim DB_Wkb As Workbook 'Database
Set Doc_Wkb = Workbooks.Open(Doc_Path)
Doc_Wkb.Worksheets(Sheet_Name).Cells.Select 'sheet_name=Sheet of the Document
Selection.UnMerge
Doc_Wkb.Worksheets(Sheet_Name).Range("A5:S" & Cells(Rows.Count, "S").End(xlUp).Row).RemoveDuplicates Columns:=16, Header:=xlYes
Set DB_Wkb = Workbooks.Open(DB_Path)
Dim Str As String
Dim Cont_Doc As Double
P = 6 ' P Declared in Module
Cont_DB = DB_Wkb.Worksheets(Sheet_name_2).Range("B:F") ' Sheet_name_2 = sheetname of DB
While Not IsEmpty(Doc_Wkb.Worksheets(Sheet_Name).Cells(P, 5))
Cont_Doc = Doc_Wkb.Worksheets(Sheet_Name).Cells(P, 5)
store = Application.VLookup(Cont_Doc, Cont_DB, 5, False)
Doc_Wkb.Worksheets(Sheet_Name).Cells(P, 20) = store
P = P + 1
Wend
Thank you so much for your help.
Update: I figured out an alternative. Using DoEvents solves this problem. Meanwhile a progress bar can be used for the looks.

PasteSpecial(): wdPasteOLEObject and wdInLine Enumerations

I have written code in Excel VBA and am currently trying to convert it to vb.NET on VS 2017.
I want to copy a table in Excel, and paste it into a Word document and also keep a live link between them so that any changes in the Excel table will be transferred to the table pasted in the Word document. I managed this in Excel VBA, however vb.NET does not recognise DataType:=wdPasteOLEObject and also Placement:=wdInLine, saying they are not declared.
The following is a sample from my code:
excelApp = New Excel.Application
excelWB = excelApp.Workbooks.Open(SurveyFormLoc)
excelApp.Visible = True
With excelApp
.Sheets("Site Details").Select
.Range("B2:I11").Copy()
End With
wdApp = CreateObject("Word.Application")
wdApp.Visible = True
wdDoc = wdApp.Documents.Open(DesignReportLoc)
With wdDoc
.Application.Selection.Find.Text = "INSERT FROM SURVEY FORM"
.Application.Selection.Find.Execute()
.Application.Selection.ParagraphFormat.Alignment = 0
End With
wdApp.Selection.PasteSpecial(Link:=True, DataType:=wdPasteOLEObject, Placement:=wdInLine, DisplayAsIcon:=False)
Does anybody know what the vb.NET equivalent is to do this?
Replace wdPasteOLEObject with the number 0.
Replace wdInLine with the number 0 also.
PasteDataType Enumeration
Placement Enumeration
You could also define the Enumeration yourself if you want to preserve the readability:
Enum WdOLEPlacement
wdFloatOverText = 1
wdInLine = 0
End Enum
Enum WdPasteDataType
wdPasteBitmap = 4
wdPasteDeviceIndependentBitmap = 5
wdPasteEnhancedMetafile = 9
wdPasteHTML = 10
wdPasteHyperlink = 7
wdPasteMetafilePicture = 3
wdPasteOLEObject = 0
wdPasteRTF = 1
wdPasteShape = 8
wdPasteText = 2
End Enum
And in your code, reference like this:
DataType:=WdPasteDataType.wdPasteOLEObject
Placement:=WdOLEPlacement.wdInLine
If you run into undefined Enumerations again, you can just go to google and paste the thing you want to look up and include the word Enum and it will usually be the first result.

Excel VBA Copying from Various cells from various Workbooks

Need some help coding in VBA Excel.
So currently, I have 100+ tables and have to manually input all the data to each table from many separate Excel file from each region.
You can view the table image here: https://i.stack.imgur.com/ftLdE.png
My current code still depends on targeting a range of cells to copy which is not feasible considering if there is a change in the rows/columns.
Is there anyway to collectively get all the data from each region's Excel file and insert it?
Or is it possible to target a header or a table name so that it can fill in automatically?
Pardon me if the solution is so simple and have been asked before.
Thank you so much for the help.
Sub Extract()
Dim x As Workbook
Dim y As Workbook
Dim OpenSource As String
Dim OpenTarget As String
OpenSource = Application.GetOpenFilename("File Type, *.xlsm")
If OpenSource = "False" Then Exit Sub
OpenTarget = Application.GetOpenFilename("File Type, *.xlsm")
If OpenTarget = "False" Then Exit Sub
'## Open both workbooks first:
Set x = Workbooks.Open(OpenSource) 'Source File 'thisworkbook can implement here?
Set y = Workbooks.Open(OpenTarget) 'Destination File
'Now, transfer values from x to y:
y.Sheets("Data").Range("C16:N16").Value = x.Sheets("Data").Range("C19:N19").Value
y.Sheets("Data").Range("C34:N34").Value = x.Sheets("Data").Range("C37:N37").Value
y.Sheets("Data").Range("C52:N52").Value = x.Sheets("Data").Range("C55:N55").Value
y.Sheets("Data").Range("C70:N70").Value = x.Sheets("Data").Range("C73:N73").Value
y.Sheets("Data").Range("C124:N124").Value = x.Sheets("Data").Range("C127:N127").Value
y.Sheets("Data").Range("C286:N286").Value = x.Sheets("Data").Range("C289:N289").Value
y.Sheets("Data").Range("R88:AC88").Value = x.Sheets("Data").Range("R91:AC91").Value
y.Sheets("Data").Range("R106:AC106").Value = x.Sheets("Data").Range("R109:AC109").Value
y.Sheets("Data").Range("R142:AC142").Value = x.Sheets("Data").Range("R145:AC145").Value
y.Sheets("Data").Range("R160:AC160").Value = x.Sheets("Data").Range("R163:AC163").Value
y.Sheets("Data").Range("R178:AC178").Value = x.Sheets("Data").Range("R181:AC181").Value
y.Sheets("Data").Range("R196:AC196").Value = x.Sheets("Data").Range("R199:AC199").Value
y.Sheets("Data").Range("R214:AC214").Value = x.Sheets("Data").Range("R217:AC217").Value
y.Sheets("Data").Range("R232:AC232").Value = x.Sheets("Data").Range("R235:AC235").Value
y.Sheets("Data").Range("R250:AC250").Value = x.Sheets("Data").Range("R253:AC253").Value
y.Sheets("Data").Range("R268:AC268").Value = x.Sheets("Data").Range("R271:AC271").Value
y.Sheets("Data").Range("AG88:AR88").Value = x.Sheets("Data").Range("AG91:AR91").Value
y.Sheets("Data").Range("AG106:AR106").Value = x.Sheets("Data").Range("A109:AR109").Value
y.Sheets("Data").Range("AG142:AR142").Value = x.Sheets("Data").Range("AG145:AR145").Value
y.Sheets("Data").Range("AG160:AR160").Value = x.Sheets("Data").Range("AG163:AR163").Value
y.Sheets("Data").Range("AG178:AR178").Value = x.Sheets("Data").Range("AG181:AR181").Value
y.Sheets("Data").Range("AG196:AR196").Value = x.Sheets("Data").Range("AG199:AR199").Value
y.Sheets("Data").Range("AG214:AR214").Value = x.Sheets("Data").Range("AG217:AR217").Value
y.Sheets("Data").Range("AG232:AR232").Value = x.Sheets("Data").Range("AG235:AR235").Value
y.Sheets("Data").Range("AG250:AR250").Value = x.Sheets("Data").Range("AG253:AR253").Value
y.Sheets("Data").Range("AG268:AR268").Value = x.Sheets("Data").Range("AG271:AR271").Value
MsgBox ("Done")
End Sub
Sure. as long as you know the starting point, you can dynamically count and copy rows, see modification to code below:
x.Sheets("Data").Range("C16:N" & Cells(Rows.Count, 14).End(xlUp).Row).Copy Destination:=y.Sheets("Data").Range("C19")
where i have put Cells(Rows.Count,14), the 14 relates to column N.
Apply the same logic to the rest and you should be fine! let me know how this works as i have not tested it :)
I think we have the Destination and Source the wrong way around as well.
How do I put the code in reverse? E.g. The source should be from row C19:N19 of the source file and to be copied to row C14:N14 of the destination file.
Sub Extract()
Dim x As Workbook
Dim y As Workbook
Dim OpenSource As String
Dim OpenTarget As String
OpenSource = Application.GetOpenFilename("File Type, *.xlsm")
If OpenSource = "False" Then Exit Sub
OpenTarget = Application.GetOpenFilename("File Type, *.xlsm")
If OpenTarget = "False" Then Exit Sub
Set x = Workbooks.Open(OpenSource) 'Source File
Set y = Workbooks.Open(OpenTarget) 'Destination File
x.Sheets("Data").Range("C14:N" & Cells(Rows.Count, 14).End(xlUp).Row).Copy Destination:=y.Sheets("Data").Range("C19")
MsgBox ("Done")
End Sub

How to find the adjacent cell value in excel using VB.NET

I am stuck with this sitaution. I read the forum and have tried numerous methods to solve this but nothings working.
Here is the scenario:
I am autogenerating an excel worksheet using vb.net. This worksheet gets populated with 200 data values in column A and 200 different data values in column B. I then find the maximum value of column B with its associated address (e.g. maxvalue = 2.59, address $B$89 ). I now need to find the value of the adjacent cell (in column A) and display that value in a message box.
Any help will be much appreciated.
Thanks
Sudhir
Dim xlsApp As Excel.Application = Nothing
Dim xlsWorkBooks As Excel.Workbooks = Nothing
Dim xlsWB As Excel.Workbook = Nothing
Try
xlsApp = New Excel.Application
xlsApp.Visible = True
xlsWorkBooks = xlsApp.Workbooks
xlsWB = xlsWorkbooks.Open("c:\my_excel_file.xls")
xlsWB.Range("B89").Select 'This will move the cursor to B89 cell
Dim myValue as String = ""
myValue = xlsWB.Activecell.Offset(0,-1).Value
'Offset(0,-1) means we are interested in the
'cell in which lies on the same row (0 for y axis)
'and to the left of the current one, by one cell
'which means -1 . If we want the cell in column D92 then
'we would use Offset(3,2)
Catch ex As Exception
Finally
xlsWB.Close()
xlsWB = Nothing
xlsApp.Quit()
xlsApp = Nothing
End Try

How can I programmatically modify an embedded bar/column chart with VBA?

I'm creating a ProcessBook display that populates an embedded Microsoft Office 11.0 Spreadsheet object (Office 2003) with a set of entries. I'm then calculating aggregate data about them; this aggregate data should not be visible in spreadsheet form onscreen, but does need to be used to generate a bar chart. The data is currently being used to populate a separate Microsoft Office 11.0 Spreadsheet object. It's organized such that the title of each bar chart is in column A and the corresponding value is in column B.
Since this is ProcessBook, I've had some difficulty even gaining access to embedded objects, but I've managed to embed and gain access to a ChartSpace object, as well as a child ChChart object. Unfortunately, I can't figure out how to either manually set the values of the bars or how to use the .SetData or .SetSpreadsheetData methods to point it to an object that I've populated.
Accessing the ChartSpace object is pretty straightforward: ThisDisplay.ChartSpace1
I can then add a Chart and access it fairly easily:
Dim objChart as ChChart
Set objChart = ThisDisplay.ChartSpace1.Charts.Add(0)
I can access my spreadsheet values pretty easily as well:
strBarName = ThisDisplay.sstChartData.Range("A2").Value
intBarVal = ThisDisplay.sstChartData.Range("B2").Value
How do I actually set the data source or manually set the values of the bars in the ChChart object? Alternatively, how do I use a different object to accomplish the same goal?
Apparently persistence is the key here. I managed to determine how to both add values manually and how to refer to the existing spreadsheet object. Both examples take heavily from the online ChChart documentation; I guess I was just tired when I attempted it in the first place and must have mistyped something somewhere.
Public Sub AddValuesToChartManually()
Dim objChart As ChChart
With ThisDisplay.ChartSpace1
Do While .Charts.Count > 0
ThisDisplay.ChartSpace1.Charts.Delete (0)
Loop
Set objChart = .Charts.Add
objChart.HasTitle = True
objChart.Title.Caption = "Chart Title"
objChart.Axes.Item(0).HasTitle = True
objChart.Axes.Item(1).HasTitle = True
objChart.Axes.Item(0).Title.Caption = "Axis 0"
objChart.Axes.Item(1).Title.Caption = "Axis 1"
objChart.HasLegend = False
Dim astrHeaders(0 To 4) As String
Dim aintValues1(0 To 4) As String
Dim aintValues2(0 To 4) As String
Dim astrSeries1(0) As String
Dim astrSeries2(0) As String
astrHeaders(0) = "AL1"
astrHeaders(1) = "AL2"
astrHeaders(2) = "AL3"
astrHeaders(3) = "AL4"
astrHeaders(4) = "AL5"
astrSeries(0) = "Series Name"
aintValues(0) = 1
aintValues(1) = 3
aintValues(2) = 17
aintValues(3) = 1
aintValues(4) = 7
objChart.Type = .Constants.chChartTypeColumnClustered
Call objChart.SetData(chDimSeriesName, .Constants.chDataLiteral, astrSeries)
Call objChart.SetData(chDimCategories, .Constants.chDataLiteral, astrHeaders)
Call objChart.SeriesCollection(0).SetData(.Constants.chDimValues, .Constants.chDataLiteral, aintValues)
End With
End Sub
Public Sub AddValuesFromSpreadsheet()
Dim objChart1 As ChChart
With ThisDisplay.ChartSpace1
Do While .Charts.Count > 0
ThisDisplay.ChartSpace1.Charts.Delete (0)
Loop
Set .DataSource = ThisDisplay.sstChartData
Set objChart1 = .Charts.Add
' Set the chart type.
objChart1.Type = .Constants.chChartTypeColumnClustered
' Display titles
objChart1.HasTitle = True
objChart1.Title.Caption = "Chart Title"
' Bind the series name to cell B1 in the first sheet of the spreadsheet
objChart1.SetData chDimSeriesNames, .Constants.chDataBound, "B1"
' Bind the category axis to cell A2:A28 in the first sheet of the spreadsheet.
objChart1.SetData chDimCategories, .Constants.chDataBound, "A2:A6"
' Bind the values of the data series to cells B2:B28 in the first sheet of the spreadsheet.
objChart1.SeriesCollection(0).SetData chDimValues, .Constants.chDataBound, "B2:B6"
End With
End Sub