Excel Visual Basic SpinButton1 does not work on second search - excel

I have a table with name and age and a command button, this button opens the customer search screen. When I search for the name Andrew brings me 3 results, I go to page 3 of 3 and perform a new search, so the arrow doesn't work, do you know where the error might be?
Public MatrizResultados As Variant
Public Total_Ocorrencias As Long
Private Sub btn_Procurar_Click()
If Me.txt_Procurar.Text = "" Then
MsgBox "Enter a name"
Else
Call ProcuraPersonalizada(Me.txt_Procurar.Text)
End If
End Sub
Private Sub Label6_Click()
End Sub
Private Sub Label7_Click()
End Sub
Private Sub SpinButton1_Change()
Dim Linha As Long
Dim TotalOcorrencias As Long
TotalOcorrencias = SpinButton1.Max + 1
Linha = MatrizResultados(SpinButton1.Value)
Label_Registros_Contador.Caption = SpinButton1.Value + 1 & " de " & TotalOcorrencias
TextBox1.Text = Plan1.Cells(Linha, 1).Value
TextBox2.Text = Plan1.Cells(Linha, 2).Value
End Sub
Private Sub ProcuraPersonalizada(ByVal TermoPesquisado As String)
Dim Busca As Range
Dim Primeira_Ocorrencia As String
Dim Resultados As String
'perform the search
Set Busca = Plan1.Cells.Find(What:=TermoPesquisado, After:=Range("A1"), LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not Busca Is Nothing Then
Primeira_Ocorrencia = Busca.Address
Resultados = Busca.Row
Do
Set Busca = Plan1.Cells.FindNext(After:=Busca)
If Not Busca.Address Like Primeira_Ocorrencia Then
Resultados = Resultados & ";" & Busca.Row
End If
Loop Until Busca.Address Like Primeira_Ocorrencia
MatrizResultados = Split(Resultados, ";")
SpinButton1.Max = UBound(MatrizResultados)
SpinButton1.Enabled = True
Label_Registros_Contador.Caption = "1 de " & UBound(MatrizResultados) + 1
TextBox1.Text = Plan1.Cells(MatrizResultados(0), 1).Value
TextBox2.Text = Plan1.Cells(MatrizResultados(0), 2).Value
Else
SpinButton1.Enabled = False
Label_Registros_Contador.Caption = ""
TextBox1.Text = ""
TextBox2.Text = ""
MsgBox "No results for '" & TermoPesquisado & "' was found."
End If
txt_Procurar.Text = ""
txt_Procurar.SetFocus
End Sub
Private Sub TextBox2_Change()
End Sub
Private Sub UserForm_Initialize()
SpinButton1.Enabled = False
Label_Registros_Contador.Caption = ""
End Sub

You just need to reset the Spin button, it thinks its still on entry 3 of 3 (you can reverse through the options and then it will be correct when you try and go forwards again).
Add this line:
SpinButton1.Value = 0
Somewhere before you start messing with it, I put it:
MatrizResultados = Split(Resultados, ";")
SpinButton1.Value = 0
SpinButton1.Max = UBound(MatrizResultados)

Related

Show data previously entered on a userform and allow data to be edited

I am creating a yard management system to keep track of parking spots in a lot.
The userform allows the user to click on a spot in the map (this would be the command button) that is open and then click update which will pull up another userform to fill out information about the truck going to that spot.
Once a user fills in the second userform, the spot changes from green to red to show that it is filled. Right now, there is no way to edit data entered for a spot.
For example, I might need to change the truck status from empty to full.
I think the best way to do this would be
if a spot is red (full and has information entered in the userform), then it will automatically pull up the second userform with the data already entered showing, so if something needs to be changed they can just type in the textbox and press update again.
if the spot is empty, it should pull up the first userform asking to update or clear the spot.
I am not sure if this is possible or the most efficient way to accomplish my goal of editing the already entered information, without having to fill out the entire userform again.
Private Sub cmdCancel_Click()
Unload Me
End Sub
Private Sub cmdClear_Click()
ActiveCell.ClearContents
ActiveCell.Interior.Color = vbGreen
Unload Me
End Sub
Private Sub cmdUpdate_Click()
UpdateInfo.Show
Unload Me
End Sub
Private Sub CommandButton1_Click()
UpdateInfo.Show
Unload Me
End Sub
Private Sub UserForm_Initialize()
lblInfo = ActiveCell.Value
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Set rngBDock = Range("BX7:CO7")
Set rngBulk = Range("BZ21:CG21")
Set rngTransT = Range("BF17:BY17")
Set rngTransT1 = Range("BG21:BY21")
Set rngTDock = Range("BL7:BW7")
Set rngEDock = Range("CP7:CT7")
Set rngNDock = Range("CU7:DC7")
Set rngFence = Range("CQ13:CV13")
Set rngNSide = Range("CW13:DB13")
Set rngGEO = Range("BG28:DD28")
Set rngNight = Range("CH21:DD21")
Set rngNewT = Range("DK31:DK65")
Set rngNewTl = Range("DI31:DI65")
Set rngOff = Range("BN40:CL40")
Set rngOffl = Range("BN42:CL42")
Set rng = Union(rngBDock, rngBulk, rngTransT, rngTransT1, rngTDock, rngEDock, rngNDock, rngFence, rngNSide, rngGEO, rngNight, rngNewT, rngNewTl, rngOff, rngOffl)
If Not Intersect(Target, rng) Is Nothing Then
CellInfo.Show
'ActiveCell.Value = cellFill
If Not IsEmpty(ActiveCell.Value) Then
Call RealTimeTracker
End If
End If
Private Sub cmdOkUpdate_Click()
Dim i As Integer, j As Integer
For i = 0 To lbxOption.ListCount - 1
If lbxOption.Selected(i) Then j = j + 1
Next i
If j = 0 Then
MsgBox "Please select an option. ", , "Warning"
Unload Me
UpdateInfo.Show
ElseIf j = 1 Then
NoFill = False
End If
strBOL = txtBOL.Value
strID = txtID.Value
details = txtDet.Value
opt = lbxOption.Value
currtime = time()
today = Format(Now(), "MM/DD/YYYY")
emp = TextBox1.Value
With ActiveCell
spot = .Offset(-1, 0)
If Len(spot) = 0 Then
spot = .Offset(1, 0)
Else
spot = spot
End If
End With
If NoFill = True Then
cellFill = ""
ElseIf NoFill = False Then
With Sheet5
.Range("A1").Value = "Time"
.Range("B1").Value = "Date"
.Range("C1").Value = "Location"
.Range("D1").Value = "Category"
.Range("E1").Value = "BOL"
.Range("f1").Value = "Trailer #"
.Range("g1").Value = "Details"
.Range("H1").Value = "EE Name"
.Range("A2").EntireRow.Insert
.Range("A2").Value = currtime
.Range("B2").Value = today
.Range("C2").Value = spot
.Range("D2").Value = opt
.Range("E2").Value = strBOL
.Range("F2").Value = strID
.Range("G2").Value = details
.Range("H2").Value = emp
.Columns("A:H").AutoFit
End With
If Not IsEmpty(opt) Then
cellFill = opt & " " & vbCrLf & "BOL (last 5 digits): " & strBOL & " " & vbCrLf & "Trailer # " & strID & " " & vbCrLf & details & "EE Name" & emp & " " & vbCrLf
ActiveCell.Value = cellFill
Call RealTimeTracker
End If
End If
Unload Me
Sheet1.Activate
End Sub

VBA MACRO Combobox is limited in data

I have a script in VBA (downloaded from internet and adjusted to my use). It is for Data Entry. But i have the problem with some Comboboxes. It is not alowing me to see the whole list of choises. It only shows 2 values instead of the 128 values.
I have tried to put it in a different column but still the same. At this moment C_06.List = [bom].Value is my problem!
Option Explicit
Dim Rng As Range, fnd As Range
Dim Ctrl As Control
Dim iRow As Integer
Dim wsAE As Worksheet
Private Sub C_02_Click()
T_ARR.Value = C_02.Column(1)
T_RENOV.Value = C_02.Column(3)
T_FINC.Value = C_02.Column(4)
T_AREA.Value = C_02.Column(9)
T_CALLE.Value = C_02.Column(11)
T_DIAS.Value = C_02.Column(12)
T_ESTATUS.Value = C_02.Column(13)
T_SUELO.Value = C_02.Column(15)
T_COLONIA.Value = C_02.Column(16)
T_CP.Value = C_02.Column(14)
T_ESTADO.Value = C_02.Column(17)
T_M2.Value = C_02.Column(20)
End Sub
Private Sub CMB_addnew_Click()
Set wsAE = Worksheets("INGRESOS")
If MsgBox("Correct entry?", vbYesNo + vbQuestion, "Check the data!") = vbNo Then Exit Sub
iRow = wsAE.Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
wsAE.Cells(iRow, 1).Resize(, 25).Value = Array(T_id.Value, C_02.Value, T_AREA.Value, T_ARR.Value, T_DATE.Value, C_CONC.Value, T_REFBANC.Value, T_PROYECTO.Value, T_CARGO.Value, T_RAD.Value, T_NRAD.Value, T_NPAGO.Value, C_METH.Value, T_RENOV.Value, T_FINC.Value, _
T_DIAS.Value, T_PAGARFEC.Value, T_SUELO.Value, T_ESTATUS.Value, T_M2.Value, T_CALLE.Value, T_COLONIA.Value, T_ESTADO.Value, T_CP.Value, _
, T_NOTA.Value)
'Columns.AutoFit
MsgBox "The new entry has been saved.", vbInformation, "Done"
For Each Ctrl In Controls
If TypeName(Ctrl) = "TextBox" Or TypeName(Ctrl) = "ComboBox" Then Ctrl.Value = ""
Next Ctrl
LB_01.ListIndex = -1
LB_01.TopIndex = 0
Call UserForm_Initialize
End Sub
Private Sub CMB_clear_Click()
For Each Ctrl In Controls
If TypeName(Ctrl) = "TextBox" Or TypeName(Ctrl) = "ComboBox" Then Ctrl.Value = ""
Next Ctrl
LB_01.ListIndex = -1
LB_01.TopIndex = 0
Call UserForm_Initialize
End Sub
Private Sub CMB_close_Click()
Unload Me
End Sub
Private Sub LB_01_Click()
T_id.Value = LB_01.Column(0)
C_02.Value = LB_01.Column(1)
T_ARR.Value = LB_01.Column(2)
T_CARGO.Value = LB_01.Column(3)
T_RENOV.Value = LB_01.Column(4)
T_FINC.Value = LB_01.Column(5)
C_METH.Value = LB_01.Column(6)
C_EMPTY.Value = LB_01.Column(7)
C_CONC.Value = LB_01.Column(8)
T_NRAD.Value = LB_01.Column(9)
T_NOTA.Value = LB_01.Column(10)
T_DIAS.Value = LB_01.Column(11)
T_PAGARFEC.Value = LB_01.Column(12)
T_NPAGO.Value = LB_01.Column(13)
C_06.Value = LB_01.Column(14)
C_BOM.Value = LB_01.Column(15)
T_CP.Value = LB_01.Column(16)
T_ESTADO.Value = LB_01.Column(17)
T_DATE.Value = LB_01.Column(18)
T_PROYECTO.Value = LB_01.Column(19)
T_RAD.Value = LB_01.Column(20)
T_AREA.Value = LB_01.Column(21)
T_CALLE.Value = LB_01.Column(22)
T_ESTATUS.Value = LB_01.Column(23)
T_SUELO.Value = LB_01.Column(24)
T_COLONIA.Value = LB_01.Column(25)
End Sub
Private Sub UserForm_Initialize()
T_id.Value = WorksheetFunction.Max([ids]) + 1
LB_01.List = [database].Value
C_02.List = [datalist].Value
C_CONC.List = [nouns].Value
C_BOM.List = [mrp].Value
C_METH.List = [BUoM].Value
C_06.List = [bom].Value
T_DATE.Value = Now
End Sub

Using VBA code to fill in data in Word from Excel. It worked for one test customer but not others when I added data and I don't understand why

I'm trying to use VBA code to extract data from a master Excel sheet into a Word document that will have a drop down list of customers at the start, and then have certain parts of the rest of it change to data dependent on that customer.
I found an example one that I copied and altered to suit my needs that is working (sort of), but I don't understand enough about why it works to get it right. When I started making it I only had data on one customer so used that info to test it as I went. However, when I filled in some data for other customers I found that it didn't work for them, only the first one. I also noticed that when I added another column to the Excel sheet, it tells me the subscript is out of range. That's lead me to believe that the code is getting the data from an out-of-date Excel sheet, and therefore not including the updated version, despite my best efforts to get it to use a new one. I hope this could be helped with some minor tweaking to my code where perhaps there is a specified range of columns that I've exceeded.
The code I used:
Option Explicit
Private Sub Document_ContentControlOnExit(ByVal oCC As ContentControl, Cancel As Boolean)
Dim arrData() As String
Dim strData As String
Dim lngIndex As Long
Select Case oCC.Title
Case "CC Conditional Dropdown List"
With oCC
If Not .ShowingPlaceholderText Then
For lngIndex = 1 To .DropdownListEntries.Count
If .Range.Text = .DropdownListEntries.Item(lngIndex) Then
strData = .DropdownListEntries.Item(lngIndex).Value
.Type = wdContentControlText
.Range.Text = strData
.Type = wdContentControlDropdownList
Exit For
End If
Next lngIndex
End If
End With
Case "Name"
If Not oCC.ShowingPlaceholderText Then
For lngIndex = 1 To oCC.DropdownListEntries.Count
If oCC.Range.Text = oCC.DropdownListEntries.Item(lngIndex) Then
arrData = Split(oCC.DropdownListEntries.Item(lngIndex).Value, "|")
Exit For
End If
Next lngIndex
With oCC
.Type = wdContentControlText
.Range.Text = arrData(0)
.Type = wdContentControlDropdownList
End With
ActiveDocument.SelectContentControlsByTag("AM").Item(1).Range.Text = Replace(arrData(1), "~", Chr(11))
ActiveDocument.SelectContentControlsByTag("CSA").Item(1).Range.Text = arrData(2)
ActiveDocument.SelectContentControlsByTag("Contract").Item(1).Range.Text = arrData(3)
ActiveDocument.SelectContentControlsByTag("Renewal").Item(1).Range.Text = arrData(4)
ActiveDocument.SelectContentControlsByTag("CurrentHR").Item(1).Range.Text = arrData(5)
ActiveDocument.SelectContentControlsByTag("RUG").Item(1).Range.Text = arrData(6)
ActiveDocument.SelectContentControlsByTag("eRMI").Item(1).Range.Text = arrData(7)
ActiveDocument.SelectContentControlsByTag("PurchasedHRSCBS").Item(1).Range.Text = arrData(8)
ActiveDocument.SelectContentControlsByTag("PurchasedMODAMEJpeRMALOD").Item(1).Range.Text = arrData(9)
ActiveDocument.SelectContentControlsByTag("ActualHRSCBS").Item(1).Range.Text = arrData(10)
ActiveDocument.SelectContentControlsByTag("ActualMODAM").Item(1).Range.Text = arrData(11)
ActiveDocument.SelectContentControlsByTag("ActualER").Item(1).Range.Text = arrData(12)
ActiveDocument.SelectContentControlsByTag("ActualEJp").Item(1).Range.Text = arrData(13)
ActiveDocument.SelectContentControlsByTag("ActualMedApp").Item(1).Range.Text = arrData(14)
ActiveDocument.SelectContentControlsByTag("ActualLoD").Item(1).Range.Text = arrData(15)
ActiveDocument.SelectContentControlsByTag("ERattainmentCons").Item(1).Range.Text = arrData(16)
ActiveDocument.SelectContentControlsByTag("ERattainmentnon-Cons").Item(1).Range.Text = arrData(17)
ActiveDocument.SelectContentControlsByTag("ERattainmentNwBN").Item(1).Range.Text = arrData(18)
ActiveDocument.SelectContentControlsByTag("ERattainmentWBN").Item(1).Range.Text = arrData(19)
ActiveDocument.SelectContentControlsByTag("ERattainmentAHPs").Item(1).Range.Text = arrData(20)
ActiveDocument.SelectContentControlsByTag("ERattainmentPharm").Item(1).Range.Text = arrData(21)
ActiveDocument.SelectContentControlsByTag("eJPAttainmentCons").Item(1).Range.Text = arrData(22)
ActiveDocument.SelectContentControlsByTag("eJPAttainmentNonCons").Item(1).Range.Text = arrData(23)
ActiveDocument.SelectContentControlsByTag("eJPAttainmentNWBN").Item(1).Range.Text = arrData(24)
ActiveDocument.SelectContentControlsByTag("eJPAttainmentAHPs").Item(1).Range.Text = arrData(25)
ActiveDocument.SelectContentControlsByTag("eJPAttainmentPharma").Item(1).Range.Text = arrData(26)
ActiveDocument.SelectContentControlsByTag("AcademyHRPropSent").Item(1).Range.Text = arrData(27)
ActiveDocument.SelectContentControlsByTag("AcademyHmPropSent").Item(1).Range.Text = arrData(28)
ActiveDocument.SelectContentControlsByTag("AcademyHRPropReturned").Item(1).Range.Text = arrData(29)
ActiveDocument.SelectContentControlsByTag("AcademyHMPropReturned").Item(1).Range.Text = arrData(30)
ActiveDocument.SelectContentControlsByTag("AcademyHRcourses").Item(1).Range.Text = arrData(31)
ActiveDocument.SelectContentControlsByTag("AcademyHMcourses").Item(1).Range.Text = arrData(32)
ActiveDocument.SelectContentControlsByTag("AcademyHREntit").Item(1).Range.Text = arrData(33)
ActiveDocument.SelectContentControlsByTag("AcademyHMEntit").Item(1).Range.Text = arrData(34)
Else
ActiveDocument.SelectContentControlsByTag("AM").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("CSA").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("Contract").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("Renewal").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTitle("CurrentHR").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("RUG").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("eRMI").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("PurchasedHRSCBS").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("PurchasedMODAMEJpeRMALOD").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("ActualHRSCBS").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("ActualMODAM").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("ActualER").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("ActualEJp").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("ActualMedApp").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("ActualLoD").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("ERattainmentCons").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("ERattainmentnon-Cons").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("ERattainmentNwBN").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("ERattainmentWBN").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("ERattainmentAHPs").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("ERattainmentPharm").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("eJPAttainmentCons").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("eJPAttainmentNonCons").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("eJPAttainmentNWBN").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("eJPAttainmentAHPs").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("eJPAttainmentPharma").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("AcademyHRPropSent").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("AcademyHmPropSent").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("AcademyHRPropReturned").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("AcademyHMPropReturned").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("AcademyHRcourses").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("AcademyHMcourses").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("AcademyHMEntit").Item(1).Range.Text = vbNullString
ActiveDocument.SelectContentControlsByTag("AcademyHREntit").Item(1).Range.Text = vbNullString
End If
Case Else
End Select
lbl_Exit:
Exit Sub
End Sub
Sub Document_Open()
Dim strWorkbook As String, strColumnData As String
Dim lngIndex As Long, lngRowIndex As Long, lngColIndex As Long
Dim arrData As Variant
Dim oCC As ContentControl, oFF As FormField, oCtrl As Control
Dim bReprotect As Boolean
Application.ScreenUpdating = False
strWorkbook = ThisDocument.Path & "\Excel Data Store.xlsx"
If Dir(strWorkbook) = "" Then
MsgBox "Cannot find the designated workbook: " & strWorkbook, vbExclamation
Exit Sub
End If
arrData = fcnExcelDataToArray(strWorkbook, "Simple List")
Set oCC = ActiveDocument.SelectContentControlsByTitle("CC Dropdown List").Item(1)
If oCC.DropdownListEntries.Item(1).Value = vbNullString Then
For lngIndex = oCC.DropdownListEntries.Count To 2 Step -1
oCC.DropdownListEntries.Item(lngIndex).Delete
Next lngIndex
Else
oCC.DropdownListEntries.Clear
End If
For lngRowIndex = 0 To UBound(arrData, 2)
oCC.DropdownListEntries.Add arrData(0, lngRowIndex), arrData(0, lngRowIndex)
Next
Set oFF = ActiveDocument.FormFields("Formfield_DD_List")
bReprotect = False
If ActiveDocument.ProtectionType <> wdNoProtection Then
ActiveDocument.Unprotect
bReprotect = True
End If
oFF.DropDown.ListEntries.Clear
For lngRowIndex = 0 To UBound(arrData, 2)
oFF.DropDown.ListEntries.Add arrData(0, lngRowIndex)
Next
If bReprotect Then ActiveDocument.Protect wdAllowOnlyFormFields, True
With ActiveX_ComboBox
.Clear
.AddItem " "
For lngRowIndex = 0 To UBound(arrData, 2)
.AddItem arrData(0, lngRowIndex)
Next
.MatchRequired = True
.Style = fmStyleDropDownList
End With
arrData = fcnExcelDataToArray(strWorkbook, "Simple Conditional List")
Set oCC = ActiveDocument.SelectContentControlsByTitle("CC Conditional Dropdown List").Item(1)
If oCC.DropdownListEntries.Item(1).Value = vbNullString Then
For lngIndex = oCC.DropdownListEntries.Count To 2 Step -1
oCC.DropdownListEntries.Item(lngIndex).Delete
Next lngIndex
Else
oCC.DropdownListEntries.Clear
End If
For lngIndex = 0 To UBound(arrData, 2)
oCC.DropdownListEntries.Add arrData(0, lngIndex), arrData(1, lngIndex)
Next
arrData = fcnExcelDataToArray(strWorkbook, "Advanced Conditional List")
Set oCC = ActiveDocument.SelectContentControlsByTitle("Name").Item(1)
If oCC.DropdownListEntries.Item(1).Value = vbNullString Then
For lngIndex = oCC.DropdownListEntries.Count To 2 Step -1
oCC.DropdownListEntries.Item(lngIndex).Delete
Next lngIndex
Else
oCC.DropdownListEntries.Clear
End If
For lngRowIndex = 0 To UBound(arrData, 2)
strColumnData = vbNullString
For lngColIndex = 1 To UBound(arrData, 1)
strColumnData = strColumnData & "|" & arrData(lngColIndex, lngRowIndex)
Next lngColIndex
strColumnData = Right(strColumnData, Len(strColumnData) - 1)
oCC.DropdownListEntries.Add arrData(0, lngRowIndex), strColumnData
Next
lbl_Exit:
Application.ScreenUpdating = True
Exit Sub
End Sub
Private Function fcnExcelDataToArray(strWorkbook As String, _
Optional strRange As String = "Sheet1", _
Optional bIsSheet As Boolean = True, _
Optional bHeaderRow As Boolean = True) As Variant
Dim oRS As Object, oConn As Object
Dim lngRows As Long
Dim strHeaderYES_NO As String
strHeaderYES_NO = "YES"
If Not bHeaderRow Then strHeaderYES_NO = "NO"
If bIsSheet Then strRange = strRange & "$]" Else strRange = strRange & "]"
Set oConn = CreateObject("ADODB.Connection")
oConn.Open ConnectionString:="Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strWorkbook & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=" & strHeaderYES_NO & """;"
Set oRS = CreateObject("ADODB.Recordset")
oRS.Open "SELECT * FROM [" & strRange, oConn, 2, 1
With oRS
.MoveLast
lngRows = .RecordCount
.MoveFirst
End With
fcnExcelDataToArray = oRS.GetRows(lngRows)
lbl_Exit:
If oRS.State = 1 Then oRS.Close
Set oRS = Nothing
If oConn.State = 1 Then oConn.Close
Set oConn = Nothing
Exit Function
End Function
I expect data dependant on a customer selected from a dropdown list to be extracted from an Excel document and filled into a Word document.
Am getting the error code:
Run-time error '9': Subscript out of range
on the line:
ActiveDocument.SelectContentControlsByTag("AcademyHMEntit").Item(1).Range.Text = arrData(34)
after adding in a column to the master Excel sheet so believe the VBA is trying to use an out of date version of the master Excel sheet.
Screenshot of the content controls below with the customer name being the dropdown list and the bits in yellow as content dependant on it

VBA Userform Listbox Conditional Logic Not Working as Intended

I have a Userform with a listbox for which I am using conditional logic to determine output values to the sheet of selected or non-selected items in the listbox. The issue is that when the Textbox (Tbl_AliasName) is blank, the code executes this:
ElseIf .Selected(k) = True And Tbl_AliasName = vbNullString Then
lstbxRow = lstbxRow + 1
Worksheets("New TRAX").Cells(lstbxRow, 3) = Trim(Cells(2, 1).Value2) & "." & .Column(1, k)
But if Tbl_AliasName is not blank then the code does nothing, but it is supposed to do this:
ElseIf .Selected(k) = True And Tbl_AliasName <> vbNullString Then
lstbxRow = lstbxRow + 1
Worksheets("New TRAX").Cells(lstbxRow, 3) = Tbl_AliasName & "." & .Column(1, k)
I have used several variations of If statements, and non of which have worked.
Below is My Code:
Option Explicit
Public Tbl_AliasName As String
Tbl_AliasName = Trim(UserForm_Finder.txtConcat.Value)
Private Sub BtnConcat_Click()
Dim k As Long, lstbxRow As Long, LR As Long
lstbxRow = 1
'****************
'This if statement works perfectly
If (Cells(2, 1).Value2 = vbNullString Or Cells(2, 2).Value2 = vbNullString) _
And Tbl_AliasName = vbNullString Then
MsgBox "You must Search for a Table or Column first.", _
vbExclamation, "Error Encountered"
Exit Sub
ElseIf (UserForm_Finder.ListBx_TblsCols.ListCount = 0 And Tbl_AliasName <> vbNullString) Then
MsgBox "You must Search for a Table or Column first.", _
vbExclamation, "Error Encountered"
'(Cells(2, 1).Value2 = vbNullString Or Cells(2, 2).Value2 = vbNullString) And _
Exit Sub
End If
With UserForm_Finder.ListBx_TblsCols
For k = 0 To .ListCount - 1
'****************
This is where the problems begin
If .Selected(k) = False Then
MsgBox "You must Select 1 or more items from the list box.", _
vbExclamation, "Error Encountered"
Exit Sub
ElseIf .Selected(k) = True And Tbl_AliasName <> vbNullString Then
lstbxRow = lstbxRow + 1
Worksheets("New TRAX").Cells(lstbxRow, 3) = Tbl_AliasName & "." & .Column(1, k)
ElseIf .Selected(k) = True And Tbl_AliasName = vbNullString Then
lstbxRow = lstbxRow + 1
Worksheets("New TRAX").Cells(lstbxRow, 3) = Trim(Cells(2, 1).Value2) & "." & .Column(1, k)
End If
Next k
End With
End Sub
My goal is to do the following:
If a Textbox (Tbl_AliasName) is not blank and the user has selected one or more items in the listbox (ListBx_TbleCols) then concatenate the Tbl_AliasName to the selected items in the listbox
If Tbl_AliasName is blank, then use the value in Cells(2,1) to concatenate to the selected Items in the list box.
I have tried the following additions:
Dim LstBxItemSelected As Boolean
'This was placed in the for loop
LstBxItemSelected = True
'this was placed outside the for loop
If LstBxItemSelected = False Then
MsgBox "You must Select 1 or more items from the list box.", _
vbExclamation, "Error Encountered"
Exit Sub
End If
Is there a better way to tell if items are selected, because I feel that the way I have it structured in my loop, the code will throw the error if everything isn't selected? Thank you in advance for any ideas, answers, or suggestions!
Note: The Listbox is populated by the click of another button on the userform which calls the following sub:
Sub FillLstBxCols()
Dim ListBx_Target As MSForms.ListBox
Dim rngSource As Range
Dim LR As Long
If Cells(2, 1).Value2 <> vbNullString Then
LR = Worksheets("New TRAX").Cells(Rows.Count, 2).End(xlUp).Row
'Set reference to the range of data to be filled
Set rngSource = Worksheets("New Trax").Range("A" & 2 & ":" & "B" & LR)
'Fill the listbox
Set ListBx_Target = UserForm_Finder.ListBx_TblsCols
With ListBx_Target
.RowSource = rngSource.Address
End With
End If
End Sub
Hard to say without sample data and expected results, but I think this is what you're looking for:
Private Sub btnConcat_Click()
Dim ws As Worksheet
Dim bSelected As Boolean
Dim sConcat As String
Dim i As Long, lRowIndex As Long
Set ws = ActiveWorkbook.Sheets("New TRAX")
lRowIndex = 1
bSelected = False
sConcat = Trim(Me.txtConcat.Text)
If Len(sConcat) = 0 Then sConcat = Trim(ws.Cells(2, "A").Value)
If Len(sConcat) = 0 Then
MsgBox "You must Search for a Table or Column first.", vbExclamation, "Error Encountered"
Exit Sub
End If
For i = 0 To Me.ListBx_TblsCols.ListCount - 1
If Me.ListBx_TblsCols.Selected(i) Then
If bSelected = False Then
bSelected = True
ws.Range("C2", ws.Cells(ws.Rows.Count, "C")).Clear 'clear previous concat results (delete this line if not needed)
End If
lRowIndex = lRowIndex + 1
ws.Cells(lRowIndex, "C").Value = sConcat & "." & Me.ListBx_TblsCols.List(i)
End If
Next i
If bSelected = False Then MsgBox "Must select at least one item from the list"
End Sub

Unload form after printing in Excel

In frmClothingPricer, when cmdPrint is pressed, frmPrint activates and is printed however many times asked for. I don't want 10+ frmPrint "active". How can I close frmPrint after each print loop? I have tried it on frmPrint "Unload Me" but that doesn't unload it either. ?? what am I missing?
Routine for printing
If Len(HowMany) = 0 Then
End
Else
Do Until i = HowMany
frmPrint.Show 'prints form on activation
i = i + 1
Unload frmPrint 'this isn't working = several forms are open
Loop
End If
frmPrint code
Private Sub UserForm_Initialize()
PrintMe
End Sub
Private Sub PrintMe()
lblPrintMonthCode.Caption = frmClothingPricer.MonthCode
lblPrintPricer.Caption = frmClothingPricer.Pricer
lblPrintCost.Caption = (frmClothingPricer.Cost * 100)
lblPrintDescription.Caption = frmClothingPricer.Description
lblPrintPrice.Caption = frmClothingPricer.Price
lblPrintItemNumber = frmClothingPricer.ItemNumber
frmPrint.PrintForm
'tried unload.me here with same results
End Sub
I solved it by keeping all the code except labels on the original form. The latest errors revolved around variables I messed up switching around. It now works perfectly (below):
form1
Public Price As Double
Public Percent As Double
Public Cost As Currency
Public Description As String
Public MonthCode As Integer
Public Pricer As String
Public ItemNumber As Double
Private Sub UserForm_Initialize()
Pricer = InputBox("Enter Your Pricer Number", vbOKOnly, "")
If Len(Pricer) = 0 Then 'Checking if Length of name is 0 characters
End
Else
End If
End Sub
Private Sub cmdSearch_Click()
Dim Response As Long
Dim NotFound As Integer
Dim arr As Variant
Dim i As Long
Dim str1 As String, str2 As String, str3 As String
lbxCost.BackColor = &H80000005
lbxCost.Locked = False
NotFound = 0
ActiveWorkbook.Sheets("Items").Activate
Response = Val("0" & Replace(txtItemNumber.Text, "-", ""))
ItemNumber = Response
If Response <> False Then
With ActiveSheet
arr = .Range("A2:D" & .Cells(.Rows.Count, "A").End(xlUp).Row)
End With
For i = 1 To UBound(arr)
If arr(i, 1) = Response Then
str1 = IIf(str1 = "", arr(i, 2), str1 & "|" & arr(i, 2))
str2 = IIf(str2 = "", arr(i, 3), str2 & "|" & arr(i, 3))
str3 = IIf(str3 = "", arr(i, 4), str3 & "|" & arr(i, 4))
End If
Next
If str1 = "" Then
MsgBox "Item Number Not Found!", vbExclamation
NotFound = 1
txtItemNumber.Text = ""
txtItemNumber.SetFocus
Else
Frame1.Visible = True
lbxDescription.List = Split(str1, "|")
lbxCost.List = Split(str2, "|")
ListBox3.List = Split(str3, "|")
End If
End If
lbxCost.ListIndex = 0
End Sub
Private Sub lbxCost_Click()
Frame2.Visible = True
End Sub
Private Sub lbxPercent_Click()
Frame3.Visible = True
lbxCost.BackColor = &H80000004
lbxCost.Locked = True
For x = 0 To lbxCost.ListCount - 1
If lbxCost.Selected(x) = True Then
Cost = lbxCost.List(x)
Description = lbxDescription.List(x)
End If
Next x
For y = 0 To lbxPercent.ListCount - 1
If lbxPercent.Selected(y) = True Then
Percent = lbxPercent.List(y)
End If
Next y
lblPrice.Caption = (Round(Cost * (1 + (Percent / 100)), 0)) - 0.01
Price = lblPrice.Caption
lblItemNumber.Caption = txtItemNumber.Text
lblDescription.Caption = Description
MonthCode = (Year(Now)) + (Month(Now)) - 1765
lblMonthCode.Caption = MonthCode
lblPricer.Caption = Pricer
cmdPrint.SetFocus
End Sub
Private Sub cmdPrint_Click()
Dim i As Integer
Dim Howmany As Double
Load frmPopup
Howmany = Val(txtQuantity.Text)
i = 1
Do Until i > Howmany
frmPopup.PrintForm
i = i + 1
Loop
lbxPercent.ListIndex = -1
Frame1.Visible = False
Frame2.Visible = False
Frame3.Visible = False
txtItemNumber.Text = ""
txtItemNumber.SetFocus
Unload frmPopup
End Sub
form2
Private Sub UserForm_Initialize()
lblPrintMonthCode.Caption = frmClothingPricer.MonthCode
lblPrintPricer.Caption = frmClothingPricer.Pricer
lblPrintCost.Caption = (frmClothingPricer.Cost * 100)
lblPrintDescription.Caption = frmClothingPricer.Description
lblPrintPrice.Caption = frmClothingPricer.Price
lblPrintItemNumber = frmClothingPricer.ItemNumber
End Sub

Resources