Add data to the table from data entry form

abbas50

Board Regular
Joined
Dec 6, 2019
Messages
51
Office Version
  1. 2016
Platform
  1. Windows
When i try to add data to my table from a userform data entry form - it goes like this ( please look at the screenshot)
some of my information goes on a row and others go to another row
please help to solve this problem

my code is
VBA Code:
Private Sub CommandButton1_Click()
Dim wks As Worksheet
Dim addnew As Range
Dim f As Range
Dim r As Range

Set wks = Sheet1
  Set r = wks.Range("B:B").Find(TextBox2.Value, , xlValues, xlWhole)
  If Not r Is Nothing Then
    MsgBox "Website  Name Already exists: " & TextBox2.Value
    Exit Sub
  End If
'Prevent duplicates in column H
  Set f = wks.Range("A:A").Find(TextBox1.Value, , xlValues, xlWhole)
  If Not f Is Nothing Then
    MsgBox "Publisher House Name Already exists: " & TextBox1.Value
    Exit Sub
  End If
'change the number for the number of controls on the userform
cNum = 27
'add the data to the selected worksheet
Set addnew = wks.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
For x = 1 To cNum
addnew = Me.Controls("TextBox" & x).Value
Set addnew = addnew.Offset(0, 1)
Next
'clear the values in the userform
For x = 1 To cNum

Next
'communicate the results
MsgBox "The values have been sent to the " & sht & " Publisher House Sheet"

Dim arrItems()
Dim cnt As Long
Dim pro As Long


    For pro = 0 To TextBox7.ListCount - 1
        If TextBox7.Selected(pro) Then
            ReDim Preserve arrItems(cnt)
            arrItems(cnt) = TextBox7.List(pro)
            cnt = cnt + 1

        End If
    Next pro

    If cnt > 0 Then
        Sheet1.Range("G" & Rows.Count).End(xlUp).Value = Join(arrItems, "|")
    End If

Dim arrItems1()
Dim op As Long
Dim om As Long


    For om = 0 To TextBox6.ListCount - 1
        If TextBox6.Selected(om) Then
            ReDim Preserve arrItems1(op)
            arrItems1(op) = TextBox6.List(om)
            op = op + 1

        End If
    Next om

    If op > 0 Then
        Sheet1.Range("F" & Rows.Count).End(xlUp).Value = Join(arrItems1, "|")
    End If
    End Sub
 

Excel Facts

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.
some of your code is stuff that I've never written. I didn't run it to test it out. but have you taken the measure necessary yet to debug? for instance, using breakpoints, cursor hovering over variable names at different points of code stoppage, the immediate window, the watch window....???
 
Upvote 0
some of your code is stuff that I've never written. I didn't run it to test it out. but have you taken the measure necessary yet to debug? for instance, using breakpoints, cursor hovering over variable names at different points of code stoppage, the immediate window, the watch window....???
i dont understand what you mean :/
 
Upvote 0
The table you're adding data to is a Structured table (you created it by using Insert>Table, or you added the headers, and then selected them and used Home>Format as table).

You're starting with an empty table. Empty tables have a blank row (the insert range) below the headers which traps the .End(xlUp) command. You're expecting that to jump to the header row.

the command
VBA Code:
Set addnew = wks.Cells(Rows.Count, 1).End(xlUp)

will set the addnew object to the blank row in the table.
However, you then offset it by 1 row, so you start by adding the first values of Name and Website to the row below the table.

I'd be inclined to suggest you utilise the table, it makes a lot of the positioning a lot simpler.

the table is a ListObject

You can reference it with code like this;

VBA Code:
Dim wks As Worksheet
Dim addnew As Range
Dim f As Range
Dim r As Range
Dim tbl as ListObject, tRow as ListRow

Set wks = Sheet1
set tbl = wks.ListObjects("Whatever the table name is") 'or set tbl=wks.ListObjects(1)

'Get a new row into the addnew object, if there are no data rows, the blank row is the "InsertRowRange".
'If there are data rows, these can be referenced as ListRows, and a new one can be added to the table with the .Add method


If Not tbl.InsertRowRange Is Nothing Then

    Set addnew = tbl.InsertRowRange
Else
    Set tRow = tbl.ListRows.Add
    Set addnew = tRow.Range
End If
 
Upvote 0
The table you're adding data to is a Structured table (you created it by using Insert>Table, or you added the headers, and then selected them and used Home>Format as table).

You're starting with an empty table. Empty tables have a blank row (the insert range) below the headers which traps the .End(xlUp) command. You're expecting that to jump to the header row.

the command
VBA Code:
Set addnew = wks.Cells(Rows.Count, 1).End(xlUp)

will set the addnew object to the blank row in the table.
However, you then offset it by 1 row, so you start by adding the first values of Name and Website to the row below the table.

I'd be inclined to suggest you utilise the table, it makes a lot of the positioning a lot simpler.

the table is a ListObject

You can reference it with code like this;

VBA Code:
Dim wks As Worksheet
Dim addnew As Range
Dim f As Range
Dim r As Range
Dim tbl as ListObject, tRow as ListRow

Set wks = Sheet1
set tbl = wks.ListObjects("Whatever the table name is") 'or set tbl=wks.ListObjects(1)

'Get a new row into the addnew object, if there are no data rows, the blank row is the "InsertRowRange".
'If there are data rows, these can be referenced as ListRows, and a new one can be added to the table with the .Add method


If Not tbl.InsertRowRange Is Nothing Then

    Set addnew = tbl.InsertRowRange
Else
    Set tRow = tbl.ListRows.Add
    Set addnew = tRow.Range
End If
appreciate your reply .. i did do manual heading then insert - Table i will try your code and i hope it works as i need to start filling for my project ty for your time :) i will let you know what happened in a bit ty again
 
Upvote 0
The table you're adding data to is a Structured table (you created it by using Insert>Table, or you added the headers, and then selected them and used Home>Format as table).

You're starting with an empty table. Empty tables have a blank row (the insert range) below the headers which traps the .End(xlUp) command. You're expecting that to jump to the header row.

the command
VBA Code:
Set addnew = wks.Cells(Rows.Count, 1).End(xlUp)

will set the addnew object to the blank row in the table.
However, you then offset it by 1 row, so you start by adding the first values of Name and Website to the row below the table.

I'd be inclined to suggest you utilise the table, it makes a lot of the positioning a lot simpler.

the table is a ListObject

You can reference it with code like this;

VBA Code:
Dim wks As Worksheet
Dim addnew As Range
Dim f As Range
Dim r As Range
Dim tbl as ListObject, tRow as ListRow

Set wks = Sheet1
set tbl = wks.ListObjects("Whatever the table name is") 'or set tbl=wks.ListObjects(1)

'Get a new row into the addnew object, if there are no data rows, the blank row is the "InsertRowRange".
'If there are data rows, these can be referenced as ListRows, and a new one can be added to the table with the .Add method


If Not tbl.InsertRowRange Is Nothing Then

    Set addnew = tbl.InsertRowRange
Else
    Set tRow = tbl.ListRows.Add
    Set addnew = tRow.Range
End If
i still keep getting same results :/ i dont know what to do :/
 
Upvote 0
OK - I'll jiggle your code around, I think I get what it's trying to do - give me an hour to get some actual employer work done ;)
 
Upvote 0
OK - I'll jiggle your code around, I think I get what it's trying to do - give me an hour to get some actual employer work done ;)
i dont know how to thank you boss ... but i wish you all the best in life :) appreciated
 
Upvote 0
OK, here goes.

I've added some comments in the code, as I'm trying to interpret what your code is up to.

VBA Code:
Private Sub CommandButton1_Click()
  
  
Dim wks As Worksheet
Dim addnew As Range
Dim f As Range
Dim r As Range
Dim tbl As ListObject, tRow As ListRow, tCol As ListColumn
Dim ctrl As Control


Set wks = Sheet1
Set tbl = wks.ListObjects("tbl_PublishHouses") 'or set tbl=wks.ListObjects(1)

'FBC - Get a new row into the addnew object, if there are no data rows, the blank row is the "InsertRowRange".
'FBC - If there are data rows, these can be referenced as ListRows, and a new one can be added to the table with the .Add method.
'FBC - if there are data rows, check for the Website/Publishing house name already existing


If Not tbl.InsertRowRange Is Nothing Then

    Set addnew = tbl.InsertRowRange
Else
    
    Set tCol = tbl.ListColumns("Website")

    Set f = tCol.DataBodyRange.Find(TextBox2.Value, , xlValues, xlWhole)
    If Not f Is Nothing Then
        MsgBox "Website  Name Already exists: " & TextBox2.Value
        Exit Sub
    End If
    
    Set tCol = tbl.ListColumns("Name")
    
    Set f = tCol.DataBodyRange.Find(TextBox1.Value, , xlValues, xlWhole)
    If Not f Is Nothing Then
        MsgBox "Publisher House Name Already exists: " & TextBox1.Value
        Exit Sub
    End If

    
    Set tRow = tbl.ListRows.Add
    Set addnew = tRow.Range
End If

'FBC - loop through controls on form looking for textboxes

For Each ctrl In Me.Controls


    If TypeName(ctrl) = "TextBox" Then
    
        'FBC - use the number in the textbox name to identify the column in the row, and set the value in that column to the value in the textbox
        
        addnew.Cells(1, Val(Right(ctrl.Name, Len(ctrl.Name) - Len("TextBox")))).Value = ctrl.Value
        
        'ctrl.Value = "" ' Clear the value in the control
        
    End If

Next ctrl


'clear the values in the userform
For x = 1 To cNum

'FBC - there was no code in here. the commented code in the loop above will clear the value of the textbox after adding it to the table in the worksheet

Next
'communicate the results
'FBC - you reference an variable/object "sht" here, but this is not declared or set in advance - I'm not clear what this is supposed to be.
MsgBox "The values have been sent to the " & sht & " Publisher House Sheet"

Dim arrItems()
Dim cnt As Long
Dim pro As Long


'You now reference "TextBox7", but use a "ListCount" property that doesn't belong to a textbox, so I assume this is actually a ListBox or a ComboBox...
'You appear to run a loop to add items to an array if they are selected, so I'm going to assume this is actually a listbox with multi-select turned on

    For pro = 0 To TextBox7.ListCount - 1
        If TextBox7.Selected(pro) Then
            ReDim Preserve arrItems(cnt)
            arrItems(cnt) = TextBox7.List(pro)
            cnt = cnt + 1

        End If
    Next pro

    If cnt > 0 Then
        addnew.Cells(1, 7).Value = Join(arrItems, "|")
    End If

Dim arrItems1()
Dim op As Long
Dim om As Long

'As Above, but now "TextBox6" appears to be a Listbox

    For om = 0 To TextBox6.ListCount - 1
        If TextBox6.Selected(om) Then
            ReDim Preserve arrItems1(op)
            arrItems1(op) = TextBox6.List(om)
            op = op + 1

        End If
    Next om

    If op > 0 Then
        addnew.Cells(1, 6) = Join(arrItems1, "|")
    End If


End Sub

I'd recommend that you spend a little time naming the objects (textboxes, listboxes etc) in a more useful way.

I'd name each object after the column in the target table that the data is going to be input into.

You can then use that to reference the objects/columns. Then, should you find you're adding new columns/objects, you don't have to worry about the order, or whether it'll break the assumption that the number in the textbox name relates to the number of the column in the table.

For example, the loop where I iterate through the Controls to pick out the textboxes and put their values into the table could be re-written like this;

VBA Code:
'FBC - loop through controls on form looking for textboxes

For Each ctrl In Me.Controls


    If TypeName(ctrl) = "TextBox" Then
    
        'FBC - Match the textbox name to a column name in the target table and add the textbox value into that column
        
        Set f = tbl.HeaderRowRange.Find(ctrl.Name, , xlValues, xlWhole)
        
        If Not f Is Nothing Then
            
            Set tCol = tbl.ListColumns(ctrl.Name)
        
            addnew.Cells(1, tCol.Index).Value = ctrl.Value
                
        End If
        
        ctrl.Value = ""
        
    End If

Next ctrl

and that would allow columns to be moved, added etc.

You'd have to have column names without spaces in your table (or replace the spaces with underscore and adapt the code to reflect that), but these are all essentially best practice things anyway.
 
Upvote 0
OK, here goes.

I've added some comments in the code, as I'm trying to interpret what your code is up to.

VBA Code:
Private Sub CommandButton1_Click()
 
 
Dim wks As Worksheet
Dim addnew As Range
Dim f As Range
Dim r As Range
Dim tbl As ListObject, tRow As ListRow, tCol As ListColumn
Dim ctrl As Control


Set wks = Sheet1
Set tbl = wks.ListObjects("tbl_PublishHouses") 'or set tbl=wks.ListObjects(1)

'FBC - Get a new row into the addnew object, if there are no data rows, the blank row is the "InsertRowRange".
'FBC - If there are data rows, these can be referenced as ListRows, and a new one can be added to the table with the .Add method.
'FBC - if there are data rows, check for the Website/Publishing house name already existing


If Not tbl.InsertRowRange Is Nothing Then

    Set addnew = tbl.InsertRowRange
Else
   
    Set tCol = tbl.ListColumns("Website")

    Set f = tCol.DataBodyRange.Find(TextBox2.Value, , xlValues, xlWhole)
    If Not f Is Nothing Then
        MsgBox "Website  Name Already exists: " & TextBox2.Value
        Exit Sub
    End If
   
    Set tCol = tbl.ListColumns("Name")
   
    Set f = tCol.DataBodyRange.Find(TextBox1.Value, , xlValues, xlWhole)
    If Not f Is Nothing Then
        MsgBox "Publisher House Name Already exists: " & TextBox1.Value
        Exit Sub
    End If

   
    Set tRow = tbl.ListRows.Add
    Set addnew = tRow.Range
End If

'FBC - loop through controls on form looking for textboxes

For Each ctrl In Me.Controls


    If TypeName(ctrl) = "TextBox" Then
   
        'FBC - use the number in the textbox name to identify the column in the row, and set the value in that column to the value in the textbox
       
        addnew.Cells(1, Val(Right(ctrl.Name, Len(ctrl.Name) - Len("TextBox")))).Value = ctrl.Value
       
        'ctrl.Value = "" ' Clear the value in the control
       
    End If

Next ctrl


'clear the values in the userform
For x = 1 To cNum

'FBC - there was no code in here. the commented code in the loop above will clear the value of the textbox after adding it to the table in the worksheet

Next
'communicate the results
'FBC - you reference an variable/object "sht" here, but this is not declared or set in advance - I'm not clear what this is supposed to be.
MsgBox "The values have been sent to the " & sht & " Publisher House Sheet"

Dim arrItems()
Dim cnt As Long
Dim pro As Long


'You now reference "TextBox7", but use a "ListCount" property that doesn't belong to a textbox, so I assume this is actually a ListBox or a ComboBox...
'You appear to run a loop to add items to an array if they are selected, so I'm going to assume this is actually a listbox with multi-select turned on

    For pro = 0 To TextBox7.ListCount - 1
        If TextBox7.Selected(pro) Then
            ReDim Preserve arrItems(cnt)
            arrItems(cnt) = TextBox7.List(pro)
            cnt = cnt + 1

        End If
    Next pro

    If cnt > 0 Then
        addnew.Cells(1, 7).Value = Join(arrItems, "|")
    End If

Dim arrItems1()
Dim op As Long
Dim om As Long

'As Above, but now "TextBox6" appears to be a Listbox

    For om = 0 To TextBox6.ListCount - 1
        If TextBox6.Selected(om) Then
            ReDim Preserve arrItems1(op)
            arrItems1(op) = TextBox6.List(om)
            op = op + 1

        End If
    Next om

    If op > 0 Then
        addnew.Cells(1, 6) = Join(arrItems1, "|")
    End If


End Sub

I'd recommend that you spend a little time naming the objects (textboxes, listboxes etc) in a more useful way.

I'd name each object after the column in the target table that the data is going to be input into.

You can then use that to reference the objects/columns. Then, should you find you're adding new columns/objects, you don't have to worry about the order, or whether it'll break the assumption that the number in the textbox name relates to the number of the column in the table.

For example, the loop where I iterate through the Controls to pick out the textboxes and put their values into the table could be re-written like this;

VBA Code:
'FBC - loop through controls on form looking for textboxes

For Each ctrl In Me.Controls


    If TypeName(ctrl) = "TextBox" Then
   
        'FBC - Match the textbox name to a column name in the target table and add the textbox value into that column
       
        Set f = tbl.HeaderRowRange.Find(ctrl.Name, , xlValues, xlWhole)
       
        If Not f Is Nothing Then
           
            Set tCol = tbl.ListColumns(ctrl.Name)
       
            addnew.Cells(1, tCol.Index).Value = ctrl.Value
               
        End If
       
        ctrl.Value = ""
       
    End If

Next ctrl

and that would allow columns to be moved, added etc.

You'd have to have column names without spaces in your table (or replace the spaces with underscore and adapt the code to reflect that), but these are all essentially best practice things anyway.
Thank you for your time i really do appreciate it :) this is way beyond me im trying to understand it i hope i do well to explain i renamed all listboxes as textboxes so my control number goes throu to 34 now i have a question after your code is working perfectly with me i have a listbox that is not getting me the details when i click on it and when you changed the code i cant figure out how to add it can you explain that to me ? like last column is entered by : i have list of names only 1 name to be picked how can i make it to be entered and then ill be sorted for good :D ty boss for your time
 
Upvote 0

Forum statistics

Threads
1,215,461
Messages
6,124,954
Members
449,198
Latest member
MhammadishaqKhan

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top