dynamic textbox input in VBA - excel

my workbook has two sheets, one which contains data and calculations, these data have been name using the name editor function. the second worksheet has a graph and a box consisting of a group of text boxes created using VBA control Active X option, this group of text boxes is to be imputted with values previously named abbove, below is a version of the code I usued, where label and TextBox are the neames of the text boxes and the other names the names of the defined cells.
This code reports a 438 message error and would not input the labeled data in the box at the wanted location. How could I make it work so that the textboxes would display the named cells they are linked too?:
Private Sub Worksheet_Activate()
Dim sType As String
Dim sUnit As String
Dim sWellname As String
Dim sDate As String
Dim sMD As String
Dim sTVD As String
Dim sMud As String
Dim sPressure As String
Dim sEMW As String
sType = ThisWorkbook.Worksheets("sheet1").cbztest.Value
sUnit = ThisWorkbook.Worksheets("sheet1").cbzPressure.Value
sWname = ThisWorkbook.Worksheets("sheet1").Range("Wname").Value
sDate = ThisWorkbook.Worksheets("sheet1").Range("date").Value
sMD = Format(ThisWorkbook.Worksheets("sheet1").Range("MD").Value, "Standard")
sTVD = Format(ThisWorkbook.Worksheets("sheet1").Range("TVD").Value, "Standard")
sMW = ThisWorkbook.Worksheets("sheet1").Range("M_W").Value
sPressure = Round(ThisWorkbook.Worksheets("sheet1").Range("P_bar").Value, 1)
sEMW = Format(ThisWorkbook.Worksheets("sheet1").Range("EMW").Value, "Standard")
sType = ThisWorkbook.Worksheets("sheet1").cbztest.Value
ActiveSheet("Label").Caption = sType
ActiveSheet("TextBox1").Text = sWname
ActiveSheet("TextBox2").Text = sDate
ActiveSheet("TextBox5").Text = sMD
ActiveSheet("TextBox6").Text = sTVD
ActiveSheet("TextBox7").Text = sMW
ActiveSheet("TextBox8").Text = sPressure
ActiveSheet("TextBox9").Text = sEMW
ActiveSheet("Label8").Caption = sType & " EMW :"
ActiveSheet("Label13").Caption = sUnit
End Sub

Try ActiveSheet.TextBox1.Text = sWname and so on

Related

Read Multiple Excel Sheets in a Listview

I am trying to read an excel file that has multiple sheets 1,2,3,4,5,6,7,8,9,10
I need to read several columns of what is in those sheets for example from the range a1: a20 and c1: c20
The result is listing it in a listview, I am trying with several suggestions that appear in the forum, but it only allows me to read one sheet and I need to read several at the same time. Anyway I put the code that I am using.
Thanks in advance
Public Class Frm_ImportarLibro
Public Function Obtenerdatos(ByVal ruta As String, ByVal hoja As String, ByVal rango As String) As DataTable
Dim cadenaConexion As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=NO';" &
"Data Source=" & ruta
Using cnn As New OleDbConnection(cadenaConexion)
Dim cmd As OleDbCommand = cnn.CreateCommand()
cmd.CommandText = String.Format("SELECT * FROM [{0}${1}]", hoja, rango)
Dim da As New OleDbDataAdapter(cmd)
Dim dtTemp As New DataTable("Prueba")
da.Fill(dtTemp)
Dim dt As DataTable = dtTemp.Clone()
Dim rows As DataRow() = dtTemp.Select()
For index As Integer = 0 To rows.Count - 1
Dim row As DataRow = rows(index)
If (row.Item(0) Is DBNull.Value) Then
Exit For
End If
dt.ImportRow(row)
Next
Return dt
End Using
End Function
I believe this would be a matter of looping through the sheets and loading a DataTable for each sheet which is then added to a DataSet. My code assumes that the same range is used for each sheet. I made the range contiguous because it would require a separate command for each non-contiguous range. I believe it would be easier to ignore the extraneous data in the resulting DataTable.
Private cadenaConexion As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=NO';Data Source="
Private rango As String = "A1:C20"
Private Function GetXLSheetNames(path As String) As List(Of String)
Dim SheetNames As New List(Of String)
Dim dt As DataTable
Using cn As New OleDbConnection(cadenaConexion & path)
cn.Open()
dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
End Using
For Each row As DataRow In dt.Rows
Dim s = row("Table_Name").ToString
SheetNames.Add(s)
Next
Return SheetNames
End Function
Public Function Obtenerdatos(ByVal ruta As String, ByVal hoja As String, ByVal rango As String) As DataSet
Dim ds As New DataSet
Dim lst = GetXLSheetNames(ruta)
Using cnn As New OleDbConnection(cadenaConexion & ruta),
cmd As New OleDbCommand()
cmd.Connection = cnn
cnn.Open()
For Each s In lst
Dim dt As New DataTable(s)
cmd.CommandText = $"SELECT * FROM [{s}{rango}]"
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
ds.Tables.Add(dt)
Next
End Using
Return ds
End Function

How to generate a reduced Excel when filtering by id in vb.net

In vb.net I have lists that contains variables of an Excel file.
Example:
Lists first Excel:
ID
WEIGHT
NAME
CAU65469
1234
jkaufman
DEX74893
1234
jdee
Second one:
ID
COLOR
VOLUME
CAU65469
YELLOW
900
DEX743413
BLUE
1500
I want to generate a third file that looks like this:
ID
WEIGHT
NAME
COLOR
VOLUME
CAU65469
1234
jkaufman
YELLOW
900
My solution is to shorten the second Excel by filtering by id
so it would only show me the data if the ID is found in both files and then comparing by coordinates.
On vb.net, how can I save the position of an Excel (index) by an ID in order to shorten the Excel?
My code in vb.net, I have the values in lists like this:
Public ID As New List(Of String)
Public ID2 As New List(Of String)
Public COLOR As New List(Of String)
Public NAME As New List(Of String)
Public WEIGHT New List(Of String)
Public VOLUME As New List(Of String)
To just fill information in a new Excel I use this code.
I use a function like this to extract the information from the Excel files.
Function extraer_valores_planilla(ByRef ruta As String) As Boolean
ExcelPackage.LicenseContext = LicenseContext.NonCommercial
Try
Dim stream = System.IO.File.OpenRead(ruta)
Dim package = New OfficeOpenXml.ExcelPackage(stream)
'// Libro
Dim Workbook = package.Workbook
'// Hojas
Dim hojas = Workbook.Worksheets
' While (Workbook.Worksheets.Count >= aux)
Dim hojaUsuarios = Workbook.Worksheets(Workbook.Worksheets.Item(0).ToString)
Dim indice As Integer = 2
While (indice < 5000)
If (IsNothing(hojaUsuarios.Cells("A" & indice).Value) = False) Then
ID.Add(hojaUsuarios.Cells("A" & indice).Value)
End If
indice += 1
End While
indice += 1
Catch EX As Exception
MsgBox(EX.ToString)
Return False
End Try
Return True
and then I fill the third Excel like this:
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
ExcelPackage.LicenseContext = LicenseContext.NonCommercial
Dim path As String = seleccionardirectorio("Excel|.xlsx")
If (String.IsNullOrWhiteSpace(path) = False) Then
Dim excel = New ExcelPackage(New FileInfo(path))
excel.Workbook.Worksheets.Add("Hoja1")
Dim aux As Integer = 1
Dim Workbook = excel.Workbook
Dim hojas = Workbook.Worksheets
Dim dict As New Dictionary(Of String, String)
Dim hoja1 = Workbook.Worksheets("Hoja1")
'DAMOS NOMBRE A LAS COLUMNAS
INICIALIZAR_PLANILLA(hoja1)
While (aux <= ID.Count)
hoja1.Cells("C" & aux + 1).Value = COLOR.Item(aux - 1)
aux += 1
End While
One of the things we (should) do when we write programs in an object oriented language, is try and move away from thinking like "I have to store 5 bits of info about an object - id, color, name, weight, volume. I'll make 5 arrays, one for each thing, and relate them all positionally so the "ID1 BLUE JOHN 50KG 200m3" data is at array index 9 in each of the five arrays"
Instead we should be thinking "I'll make a class with 5 properties, and I'll create instances of it and fill them" - this way the items of data don't remain related purely because they "just happen to all be at position 9 in some arrays" but instead are all together and representing an object. Nearly line of code you write in VB uses something that obeys this notion - you should too
Public Class Whatever
Public Property ID As String
Public Property Color As String
Public Property Name As String
Public Property Weight As String
Public Property Volume As String
End Class
Next we use some collection that supports looking things up, like a Dictionary:
Function extraer_valores_planilla(ByRef ruta As String, isFirstExcel as Moolean) As Boolean
... 'put code that opens file here - i removed for clarity
Dim das New Dictionary(Of String, Whatever)
Dim indice As Integer = 2
While (indice < 5000)
If (IsNothing(hojaUsuarios.Cells("A" & indice).Value)) Then
indice += 1
Continue While
End If
Dim id = hojaUsuarios.Cells("A" & indice).Value
If Not d.ContainsKey(id) Then d(id) = New Whatever
d(id).ID = id
If isFirstExcel Then
d(id).Weight = hojaUsuarios.Cells("B" & indice).Value
d(id).Name = hojaUsuarios.Cells("C" & indice).Value
Else
d(id).Color = hojaUsuarios.Cells("B" & indice).Value
d(id).Volume = hojaUsuarios.Cells("C" & indice).Value
indice += 1
End While
The posted code does not show how ID2 Color, Volume, Weight, Name lists come to be populated with anything. I've assumed that WEIGHT/COLOR is in column B, and NAME/VOLUME is in column C
At the end of this operation you have a dictionary that has ID strings mapping to Whatever objects... And those objects Will have two or four properties filled in depending on if their ID was present in one file or the other

validate strings in an excel in vb.net

I have a question, in vb.net, how can i validate that 2 values are the same in an excel in vb.net
for example i have defined 3 list
Public NSPS As New List(Of String)
Public CONTAINER As New List(Of String)
Public CONTAINER2 As New List(Of String)
I have 2 excel files where CONTAINER and CONTAINER2 are id's
So i need to create a third excel file that filters only the id's that repeat themselves in the 2 excel
meaning if i have an id: CARU9891569 in the 2 files, only then it transfers to the generated excel
and the 2 excel's have some extra information, for example: excel 1 has the variables: DELIVERY, CONTAINER, VOLUME.
the second excel has the variables: NSPS, NPOS, PACKAGES, CONTAINER2
SO the generated excel needs to have all of the variables: DELIVERY, CONTAINER, VOLUME, NSPS, NPOS, PACKAGES. using CONTAINER as the filter
to just fill information in a new excel i use this code
i use a function like this to extract the information from the excel files
Function extraer_valores_planilla(ByRef ruta As String) As Boolean
ExcelPackage.LicenseContext = LicenseContext.NonCommercial
Try
Dim stream = System.IO.File.OpenRead(ruta)
Dim package = New OfficeOpenXml.ExcelPackage(stream)
'// Libro
Dim Workbook = package.Workbook
'// Hojas
Dim hojas = Workbook.Worksheets
' While (Workbook.Worksheets.Count >= aux)
Dim hojaUsuarios = Workbook.Worksheets(Workbook.Worksheets.Item(0).ToString)
Dim indice As Integer = 2
While (indice < 5000)
'Numero entrega'
If (IsNothing(hojaUsuarios.Cells("A" & indice).Value) = False) Then
NSPS.Add(hojaUsuarios.Cells("A" & indice).Value)
End If
indice += 1
End While
indice += 1
Catch EX As Exception
MsgBox(EX.ToString)
Return False
End Try
Return True
and then i fill the third excel like this
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
ExcelPackage.LicenseContext = LicenseContext.NonCommercial
Dim path As String = seleccionardirectorio("Excel|.xlsx")
If (String.IsNullOrWhiteSpace(path) = False) Then
Dim excel = New ExcelPackage(New FileInfo(path))
excel.Workbook.Worksheets.Add("Hoja1")
Dim aux As Integer = 1
Dim Workbook = excel.Workbook
Dim hojas = Workbook.Worksheets
Dim dict As New Dictionary(Of String, String)
Dim hoja1 = Workbook.Worksheets("Hoja1")
'DAMOS NOMBRE A LAS COLUMNAS
INICIALIZAR_PLANILLA(hoja1)
While (aux <= CONTAINER.Count)
hoja1.Cells("C" & aux + 1).Value = ENTREGA.Item(aux - 1)
aux += 1
End While
this is the same for all variables i just resume for you guys and this works just fine.
should i use 2 cicles to filter the excel, maybe a for each, sorry i am new to programing and i am stuck in this part
any ideas would be helpfull
Thanks in advance!
yes, use 2 for each loops.
for each item in list
for each otheritem in list2
if item = otheritem then
' These items match
end if
next
next
Replace the dummy variables with yours

How to export comma delimited data to excel sheet, but each row is a new excel sheet

i have a comma delimited text file as follows
RLGAcct#,PAYMENT_AMOUNT,TRANSACTION_DATE,CONSUMER_NAME,CONSUMER_ADD_STREET,CONSUMER_ADD_CSZ,CONSUMER_PHONE,CONSUMER_EMAIL,LAST_FOUR
ZTEST01,50.00,11/15/2018,ROBERT R SMITH,12345 SOME STREET,60046,,adam#adamparks.com,2224
ZTEST02,100.00,11/15/2018,ROBERT JONES,5215 OLD ORCHARD RD,60077,,adam#adamparks.com,2223
ZTEST03,75.00,11/15/2018,JAMES B MCDONALD,4522 N CENTRAL PARK AVE APT 2,60625,,adam#adamparks.com,2222
ZTEST04,80.00,11/15/2018,JOHN Q DOE,919 W 33RD PL 2ND FL,60608,,adam#adamparks.com,2221
ZTEST05,60.00,11/15/2018,SAMANTHAN STEVENSON,123 MAIN ST,60610,,adam#adamparks.com,2220
I need to export this to excel so that each value between a comma is inserted into a column in excel
So
ZTEST01 is in A1,
50.00 is in B1
11/15/2018 in C1 ...
The thing is i need each row to be inserted into a newly created excel worksheet.
The code i have is as follows:
Dim xlApp As New Excel.Application
Dim xlWorkbook As Excel.Workbook
Dim xlWorksheet As Excel.Worksheet
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'xlWorkbook = xlApp.workboos.Add() using this later once i have the parsing figured out
Dim columns As New List(Of String)
Dim ccPayment = "C:\Users\XBorja.RESURGENCE\Downloads\Payments_Credit.txt"
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(ccPayment)
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
' Include code here to handle the row.
For Each r In currentRow
columns.Add(r)
C
Next r
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
'Dim index0 = columns(0)
'Dim index1 = columns(1)
'Dim index2 = columns(3)
'Dim index3 = columns(3)
'Dim index4 = columns(4)
'Dim index5 = columns(5)
'Dim index6 = columns(6)
'Dim index7 = columns(7)
'Dim index8 = columns(8)
'Console.WriteLine(index0 & index1 & index2 & index3 & index4 & index5 & index6 & index7 & index8)
End Using
For Each r In columns
Console.WriteLine(r)
Next
end sub
As you can see I was trying to see if i could index these so that i could possibly equate each one to a cell in excel.
The other problem is that this text file changes daily. The columns are always set (9 columns) but the rows change dynamically daily based on how many transactions we get.
I would recommend using the EPPlus package which is available via NuGet. It removes the COM challenges of working with Excel and works by reading and writing the XLSX spreadsheet files.
The following sample does what you where asking:
Private Sub btnStackOverflowQuestion_Click(sender As Object, e As EventArgs) Handles btnStackOverflowQuestion.Click
Dim ccPayment As String = "C:\temp\so.csv"
Using pkg As New ExcelPackage()
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(ccPayment)
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim sheetCount As Integer
While Not MyReader.EndOfData
sheetCount += 1
Dim newSheet As ExcelWorksheet = pkg.Workbook.Worksheets.Add($"Sheet{sheetCount}")
Try
Dim currentRow As String() = MyReader.ReadFields()
Dim columnCount As Integer = 0
For Each r In currentRow
columnCount += 1
newSheet.Cells(1, columnCount).Value = r
Next r
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
Dim fi As New FileInfo("C:\temp\so.xlsx")
pkg.SaveAs(fi)
End Using
End Sub

How to write to excel from vba

I am trying to create a button on my Access form that takes the current entry and writes the information to an Excel doc
Public Sub ExportExcel()
Dim ObjEx As Object
Dim WhatIsThisVariableFor As Object
Dim Selec As Object
Dim Column As Integer
Dim Row As Integer
Dim CustName As String
Dim Org As String
Dim Contact As String
Dim Product As String
Dim Quantity As Integer
Dim rst As DAO.Recordset
Set ObjEx = CreateObject("EXCEL.APPLICATION")
Set WhatIsThisVariableFor = ObjEx.Workbooks.Add
'Set rst = CurrentDb.OpenRecordset("Select") <---- This will be used when I get the code working
Column = 1
Row = 1
CustName = "Test" '<---- This is only used for the test
Cells(Row, Column) = CustName
ObjEx.Visible = True
Set Selec = ObjEx.Selection
End Sub
This code creates the Excel doc, but leaves it blank. I think that the Cells(Row, Column) command isn't working because it would have to be called from within excel? I'm not sure (I am very new to VBA)
How can I write to the spreadsheet cells from within Access?
You need to qualify your Cells() function to Excel's application object.
ObjEx.ActiveSheet.Cells(Row, Column).Value = CustName
I would recommend that you also choose the worksheet object explicitly:
Dim ws As object
Set ws = ObjEx.Worksheets("Sheet1")
ws.Cells(row, column).value = CustName

Resources