Buttons To Add A Row and Add A column Bug? - vba

I have a table as you can see in the image. The add row and add column button when pressed takes a user input meaning if the user wants the column in lets say C of the table it gets generated; same for the row button.
If I added a column in C using the column button and I added a row at line 5 using the row button look at what occurs:
Notice column C how the colors are distorted??
The only time this does not occur is if the user entered values that created rows and columns at the end of the table.
Add Row button code :
Private Sub CommandButton21_Click()
Dim varUserInput As Variant
Dim inpt As String
Dim oLo As ListObject
Dim RowNum
inpt = MsgBox("Do You Want To Add A Row At The END Of The Table?", vbYesNo + vbQuestion, "Add Row Choice") 'user input
If inpt = vbNo Then
' add row to table 'runs if condition is user selected no
varUserInput = InputBox("Enter The Row Number You Want To Generate:", _
"What Row?")
If varUserInput = "" Then Exit Sub
RowNum = varUserInput 'adds row based on user input
Rows(RowNum & ":" & RowNum).Insert shift:=xlDown
Rows(RowNum - 1 & ":" & RowNum - 1).Copy Range("A" & RowNum)
Range(RowNum & ":" & RowNum).ClearContents
Else
Set oLo = ActiveSheet.ListObjects(1) 'first table on sheet
With oLo
.ListRows.Add AlwaysInsert:=True 'adds row to end of table
.Range.Rows(.Range.Rows.Count).RowHeight = 30
End With
End If
End Sub
Add Column button:
Private Sub CommandButton22_Click()
' add column to table
Dim userinput As String
Dim QuestionToMessageBox As String
Dim colIndex As Variant
Dim StrtRow As Long, EndRow As Long, i As Long
Dim oLo As ListObject
userinput = MsgBox("Do you want to add the column at the END of the table?", vbYesNo + vbQuestion, "Add Column Choice") 'user input
If userinput = vbNo Then 'condition if no is selected
On Error GoTo Canceled '
colIndex = Application.InputBox("Enter a column that you want to add: ", "What column?")
If colIndex = "" Then Exit Sub
With ThisWorkbook.Sheets("Sheet1")
.Columns(colIndex).Insert shift:=xlRight '<--| reference column you want to insert
'sheet row numbers from table rows
Set oLo = .ListObjects(1) '<~~ first table on sheet
With oLo
StrtRow = .ListRows(1).Range.Row
EndRow = .ListRows.Count + StrtRow - 1
End With
For i = StrtRow To EndRow
.Cells(i, colIndex).Interior.Color = .Cells(i, 1).DisplayFormat.Interior.Color
Next i
End With
Else 'condition if yes is selected
Set oLo = ActiveSheet.ListObjects(1) 'first table on sheet
With oLo
.ListColumns.Add
.ListColumns(.ListColumns.Count).Range.ColumnWidth = 25
End With
'macro loops through to end of table to generate the proper around column lines
Range("Table1[[#Headers],[Stages]]").Select
Do Until ActiveCell.Value = ""
ActiveCell.Offset(0, 1).Activate
Loop
ActiveCell.Offset(0, -1).Activate
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Selection.Borders(xlEdgeLeft).LineStyle = xlNone
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
Selection.Borders(xlEdgeRight).LineStyle = xlNone
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
End If
Canceled:
End Sub

Because you're dealing with a ListObject the formatting should just work, so I removed all the code that was supposed to format the table. I may have missed something and you'll need to add it back.
You had an On Error Goto Cancelled statement at the beginning of your column procedure which was basically an On Error Exit Sub statement. Unless you were very clear on what errors you expected your code could quit at any error with unexpected or misunderstood results.
Below is my attempt to simplify both routines. I moved things around a lot to try to avoid repetition, got rid of some Variant variables and made other changes.
I also changed the InputBox to an Application.InputBox, which allows you to specify the input type. This means that a blank response will throw up a confusing message to the user, though, so I put Application.DisplayAlerts around the InputBox prompt to suppress the message.
I hope this works as is, I expect that something will be off from what you want. Hopefully though it will get you partway there and show you some new tricks!
Private Sub CommandButton21_Click()
'add row to table
Dim InputPosition As Long
Dim InputEndOfTable As VbMsgBoxResult
Dim oLo As ListObject
Set oLo = ActiveSheet.ListObjects(1) '
With oLo
InputEndOfTable = MsgBox("Do You Want To Add A Row At The END Of The Table?", vbYesNo + vbQuestion, "Add Row Choice")
If InputEndOfTable = vbNo Then
Application.DisplayAlerts = False
InputPosition = Application.InputBox(Prompt:="Enter The Row Number You Want To Add:", Title:="What Row?", Type:=1)
Application.DisplayAlerts = True
Else
InputPosition = .Range.Rows.Count + 1
End If
If InputPosition = 0 Then Exit Sub
If InputEndOfTable = vbYes Then
.ListRows.Add
Else
.ListRows.Add InputPosition
End If
.Range.Rows(InputPosition).RowHeight = 30
End With
End Sub
Private Sub CommandButton22_Click()
'add column to table
Dim InputPosition As Long
Dim InputEndOfTable As VbMsgBoxResult
Dim oLo As ListObject
Set oLo = ActiveSheet.ListObjects(1) '
With oLo
InputEndOfTable = MsgBox("Do You Want To Add A Column At The END Of The Table?", vbYesNo + vbQuestion, "Add column Choice")
If InputEndOfTable = vbNo Then
Application.DisplayAlerts = False
InputPosition = Application.InputBox(Prompt:="Enter The Column Number You Want To Add:", Title:="What Column?", Type:=1)
Application.DisplayAlerts = True
Else
InputPosition = .Range.Columns.Count + 1
End If
If InputPosition = 0 Then Exit Sub
If InputEndOfTable = vbYes Then
.ListColumns.Add
Else
.ListColumns.Add InputPosition
End If
.ListColumns(InputPosition).Range.ColumnWidth = 25
End With
End Sub

Related

using checkboxes with userform

I have an user form designed with three listboxes.
The 3 listboxes are populated by the location from three different sheets.
By selecting the listbox, the user can filter the data in the sheet "Data".
if the user is selecting the "BBE Bebra" from the Listbox1. then he could find the filtered result of Bebra in the sheet.
Similary, if the user is selecting from the Listbox2, the same procedure is followed and if the user is selecting from listbox3, the same procedure is followed.
The user can also, select all the three checkbox and looks for the filtered result in the sheet.
I have a issues with the working code.
If I am selecting the checkboxes and click "Filter" then I always see the filtered result. The next time I click on the Filter Button I would like to see the whole data sheet with filters clear and checkboxes cleared.
Can someone tell how I can do it ?
Below is the code, I am using in the filter button
Sub DoFilter()
Dim strCriteria() As String
Dim strCriteria2() As String
Dim strcriteria3() As String
Dim arrIdx As Integer
Dim arrIdx2 As Integer
Dim arrIdx3 As Integer
Dim xRow As Integer
Dim arrCounter As Integer
Dim lo As ListObject
arrIdx = 0
arrIdx2 = 0
arrIdx3 = 0
For xRow = 2 To Last(1, List.Cells)
If List.Cells(xRow, 2) = True Then
ReDim Preserve strCriteria(0 To arrIdx)
strCriteria(arrIdx) = List.Cells(xRow, 3)
arrIdx = arrIdx + 1
End If
Next xRow
For xRow = 2 To Last(1, List.Cells)
If List_Man.Cells(xRow, 2) = True Then
ReDim Preserve strCriteria2(0 To arrIdx2)
strCriteria2(arrIdx2) = List_Man.Cells(xRow, 3)
arrIdx2 = arrIdx2 + 1
End If
Next xRow
For xRow = 2 To Last(1, List.Cells)
If List_S.Cells(xRow, 2) = True Then
ReDim Preserve strcriteria3(0 To arrIdx3)
strcriteria3(arrIdx3) = List_S.Cells(xRow, 3)
arrIdx3 = arrIdx3 + 1
End If
Next xRow
Set Ws = ThisWorkbook.Sheets("Data")
Set lo = Ws.ListObjects("Table7")
If arrIdx = 0 And arrIdx2 = 0 And arrIdx3 = 0 Then
'Ws.UsedRange.AutoFilter
Else
With Ws
With lo
'.AutoFilterMode = True
' .UsedRange.AutoFilter
If arrIdx <> 0 Then
.Range.AutoFilter field:=13, Criteria1:=Array(strCriteria), Operator:=xlFilterValues
End If
If arrIdx2 <> 0 Then
.Range.AutoFilter field:=14, Criteria1:=Array(strCriteria2), Operator:=xlFilterValues
End If
If arrIdx3 <> 0 Then
.Range.AutoFilter field:=15, Criteria1:=Array(strcriteria3), Operator:=xlFilterValues
End If
If .AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count = 1 Then
MsgBox " Your filter has no result"
End If
End With
End With
Dim i As Long
On Error Resume Next
With ThisWorkbook.Worksheets("Dev").PivotTables("PivotTable1").PivotFields("Lo.")
.ClearAllFilters
For i = 1 To .PivotItems.Count
.PivotItems(i).Visible = False
Next
For arrCounter = LBound(strCriteria) To UBound(strCriteria)
.PivotItems(strCriteria(arrCounter)).Visible = True
Next arrCounter
End With
End If
End Sub
I call the function do filter in my button "Filter".
with the button "exit" I always have the
following code
Private Sub CBExit_Click()
If ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
Sheets("Dev").Select
Sheets("Dev").PivotTables("PivotTable1").PivotFields("Development Loc.").ClearAllFilters
Unload Me
End Sub
You will need to keep track of your current state using some sort of flag. I would do something like the following:
Private Sub Filter_Click()
If Filter.Caption = "Filter" Then
DoFilter
Filter.Caption = "Unfilter"
Else
'do logic to clear
Filter.Caption = "Filter"
End If
End Sub
This has the added benefit of telling the user what the next click of the button will do.

Alternative to Vlookup in VBA?

A strange question perhaps, but is there an alternative way of opening a workbook, searching for a particular reference in a column, and then pulling the data from a another column in that row using VBA, without using VLookup?
The table I am trying to get data from contains a mixture of numbers, text, dates, and the lookup value is often >13 digits long.
I sort of had something working with VLookup, but it was too inconsistent - every so often it would just break because the data type didn't match. An awful lot of 'type mismatch' or 'ByRef' errors - I'd get one right and then another breaks.
Unfortunately I don't know enough to know what to search to get me in the right direction.
If it helps explain what I'm trying to do, here's my code using VLookup that errors all the time:
Sub getData()
Application.EnableEvents = False
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlManual
Dim wb As Workbook, src As Workbook
Dim srcRange As Range
Dim InputString
Dim strStatus
Dim strStatusNum
Dim strD1
Dim I As Integer
Set wb = ActiveWorkbook
I = 7
Set src = Workbooks.Open("D:\Files\test2.xlsx", True, True)
With src.Sheets(1)
Set srcRange = .Range(.Range("A1"), .Range("H1").End(xlDown))
End With
Do While wb.ActiveSheet.Cells(I, 1) <> ""
'Makes sure src.Close is called if errors
'On Error Resume Next
InputString = wb.Worksheets("Sheet 1").Cells(I, 1)
strStatus = Application.VLookup(InputString, srcRange, 3, False)
strD1 = Application.VLookup(InputString, srcRange, 4, False)
'Convert strStatus to actual number e.g. "03. no d1"
strStatusNum = Left(strStatus, 2)
wb.Worksheets("Sheet 1").Cells(I, 4) = strStatusNum
If (strStatusNum <> 3) Then
wb.Worksheets("Sheet 1").Cells(I, 2) = "Not at 03. No Work Order"
ElseIf (strStatusNum = 3) And (strD1 <> "") Then
wb.Worksheets("Sheet 1").Cells(I, 2) = "D1 Received"
wb.Worksheets("Sheet 1").Cells(I, 3) = strD1
Else
wb.Worksheets("Sheet 1").Cells(I, 2) = "No D1"
End If
I = I + 1
Loop
src.Close (False)
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Calculation = xlAutomatic
End Sub
EDIT: Corrected some syntax.
You can use the Find method of the Range object, in your case of the column. The return value is the first cell (represented as another Range object) with a matching value, unless there is no match at all. Then Nothing is returned.
On the returned (single cell) range you can use the EntireRow method to get a Range that represents all the cells on the row of the found cell. On the returned (row) range you can use the Cells method to select the cell matching the column in the same row, that you want to return (again represented as another Range object).
By the way, a more flexible alternative to VLOOKUP in workbook functions is a combination of INDEX and MATCH.
Untested but compiled:
Sub getData()
Dim src As Workbook
Dim srcRange As Range
Dim strStatus, strStatusNum, strD1
Dim m, rw As Range
Set rw = ActiveSheet.Rows(7)
Set src = Workbooks.Open("D:\Files\test2.xlsx", True, True)
With src.Sheets(1)
Set srcRange = .Range(.Range("A1"), .Range("H1").End(xlDown))
End With
Do While rw.Cells(1).Value <> ""
m = Application.Match(rw.Cells(1), srcRange.Columns(1), 0)
If Not IsError(m) Then 'proceed only if got match
strStatus = srcRange.Cells(m, 3).Value
strD1 = srcRange.Cells(m, 4).Value
strStatusNum = Left(strStatus, 2)
rw.Cells(4).Value = strStatusNum
If strStatusNum <> 3 Then
rw.Cells(2) = "Not at 03. No Work Order"
ElseIf strStatusNum = 3 And strD1 <> "" Then
rw.Cells(2) = "D1 Received"
rw.Cells(3) = strD1
Else
rw.Cells(2) = "No D1"
End If
End If
Set rw = rw.Offset(1, 0)
Loop
src.Close False
End Sub
you may be after this refactoring of your code
Sub getData()
Dim wbRng As Range, cell As Range, f As Range
Dim strStatus, strStatusNum, strD1
Application.EnableEvents = False
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlManual
With ActiveWorkbook.ActiveSheet
Set wbRng = .Range("A7:A" & WorksheetFunction.Max(7, .Cells(.Rows.count, 1).End(xlUp).Row)) '<--| set the range of values to be searched for
If WorksheetFunction.CountA(wbRng) = 0 Then Exit Sub '<--| exit if no values under row 7
Set wbRng = wbRng.SpecialCells(xlCellTypeConstants) '<--| narrow the range of values to be searched for down to not blank values only
End With
With Workbooks.Open("D:\Files\test2.xlsx", True, True).Sheets(1) '<--| open wanted workbook and reference its first sheet
With .Range("A1:A" & .Cells(.Rows.count, "H").End(xlUp).Row) '<--| reference its column A range from row 1 down to column H last not empty cell (this is your former "srcRange")
For Each cell In wbRng.SpecialCells(xlCellTypeConstants) '<--| loop through range of values to be searched for
Set f = .Find(what:=cell.Value, lookat:=xlWhole, LookIn:=xlValues) '<--| look referenced range for current value to be searched for
If Not f Is Nothing Then '<--| if found
strStatus = f.Offset(, 2).Value
strD1 = f.Offset(, 3).Value
'Convert strStatus to actual number e.g. "03. no d1"
strStatusNum = val(Left(strStatus, 2)) '<--| use 'Val()' function to convert string "03" to "3"
cell.Offset(, 3) = strStatusNum
Select Case True
Case strStatusNum <> 3
cell.Offset(, 1).Value = "Not at 03. No Work Order"
Case strStatusNum = 3 And (strD1 <> "")
cell.Offset(, 1).Resize(, 2).Value = Array("D1 Received", strD1)
Case Else
cell.Offset(, 1).Value = "No D1"
End Select
End If
Next
End With
.Parent.Close False
End With
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Calculation = xlAutomatic
End Sub

How can I delete an old entry in a table when inserting a new one that maches 3 conditions using VBA in Excel?

So it's a bit tricky for me since I started learning this 3 days ago...
I have a table with 4 columns: Station name | Date | Program name | Status
When I insert a new record, it will match older ones - but the date will always be different.
I need a code to add to my code that will allow an automatic search of similar records by : Station Name + Program Name - but only for those in the current month, and delete the old existing record before writing in the new one.
This is my current code connected to a button:
Sub OK()
Application.ScreenUpdating = False
' Check if all data was filled
With Empt
If IsEmpty(Sheet1.Range("D4").Value) = True Then
MsgBox "Please fill all fields"
' ElseIf IsEmpty(Sheet1.Range("E4").Value) = True Then
'MsgBox "Please fill all fields"
ElseIf IsEmpty(Sheet1.Range("F4").Value) = True Then
MsgBox "Please fill all fields"
ElseIf IsEmpty(Sheet1.Range("G4").Value) = True Then
MsgBox "Please fill all fields"
Else
'Insert data to table
Sheet1.Range("E4").Value = Now()
Sheet1.Range("D4:G4").Copy
Sheet1.Range("A10").Rows("1:1").Insert Shift:=xlDown
MsgBox "All data have been copied!"
Sheet1.Range("D4:G4").ClearContents
'Sheet1.Range("E4").Value = "Auto Fill"
End If
End With
'CHANGE COLOR OF CELLS
With colrng
NonEmp = Sheet1.Application.CountA(Range("D10:D100000"))
Set MyPlage = Range("D10:D10" & NonEmp)
For Each Cell In MyPlage
Select Case Cell.Value
Case Is = "Completed"
Cell.Interior.ColorIndex = 43
Case Is = "Waiting"
Cell.Interior.ColorIndex = 3
Case Is = "Uploading"
Cell.Interior.ColorIndex = 6
Case Else
Cell.EntireRow.Interior.ColorIndex = xlNone
End Select
Next
End With
' Save records
Sheet1.Range("A10:E50000").Validation.Delete
ThisWorkbook.Save
End Sub
Can someone help please?
Option Explicit
Public Sub OK()
Dim ws As Worksheet, ur As Range, lr As Long, inc As Range, ref As Range
Set ws = Worksheets("Main")
Set inc = ws.Range("D4:G4") 'Insert Data
Set ref = ws.Range("A9") 'Station
With ws
lr = .Cells(.Rows.Count, 4).End(xlUp).Row
If inputIsValid(.Range("D4,F4,G4")) Then
Application.ScreenUpdating = False
Set ur = .Range(ref, "D" & lr)
removePrev ur, .Range("D4"), .Range("F4")
.Range("E4").Value = Now
inc.Copy
ref.Rows(2).Insert Shift:=xlDown
inc.ClearContents
With ref.Offset(1, 3)
Select Case .Value2
Case "Completed": .Interior.ColorIndex = 43
Case "Waiting": .Interior.ColorIndex = 3
Case "Uploading": .Interior.ColorIndex = 6
End Select
End With
.Range("D4").Activate
ThisWorkbook.Save
Application.ScreenUpdating = True
End If
End With
End Sub
Private Function inputIsValid(ByRef inRng As Range) As Boolean
Dim cel As Range, result As Boolean, invRng As Range
result = True
For Each cel In inRng
If Len(cel) = 0 Then
If invRng Is Nothing Then Set invRng = cel Else Set invRng = Union(invRng, cel)
result = False
End If
Next
If Not result Then
invRng.Interior.Color = vbBlue
MsgBox "Please enter values in blue cell(s)"
invRng.Interior.ColorIndex = xlColorIndexAutomatic
ThisWorkbook.Saved = True
End If
inputIsValid = result
End Function
Private Sub removePrev(ByRef rng As Range, ByVal sn As String, pn As String)
Dim v As Range
With rng
Set v = rng.Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count)
On Error Resume Next
.AutoFilter Field:=1, Criteria1:=sn
If v.SpecialCells(xlCellTypeVisible).Count > 1 Then
.AutoFilter Field:=2, Criteria1:=xlFilterThisMonth, Operator:=xlFilterDynamic
If v.SpecialCells(xlCellTypeVisible).Count > 1 Then
.AutoFilter Field:=3, Criteria1:=pn
If .SpecialCells(xlCellTypeVisible).Count > 1 Then
v.SpecialCells(xlCellTypeVisible).Rows.EntireRow.Delete
End If
End If
End If
.AutoFilter
End With
End Sub
It works on the following test file:
.
Note: The last sub (showStatus) can be replaced with 3 Conditional Formatting Rules:

Find if a given value is in a cell, if so then try next value until unique

I have the below sub that checks on a separate worksheet if the created number in textbox8 already exists, at the moment there is a message box that alerts the user that the part number already exists, they have to click OK, then the number is incremented by 1, the process is repeated until a unique number is found. This is the written to the worksheet along with some other data.
What I need to do is remove the message box so it will automatically search and find the next available number.
I added the following code to the sub, but this has no effect:
Application.DisplayAlerts = False
MsgBox "This already exists"
SendKeys "{ENTER}"
Application.DisplayAlerts = True
code
'Create part number and check
Private Sub CommandButton2_Click()
With TextBox26
If myreset = True Then
.Tag = 0
myreset = False
End If
.Tag = Val(.Tag) + 1
.Text = "-" & VBA.Format(Val(.Tag), "0000")
End With
Dim iNum(1 To 8) As String
iNum(1) = TextBox24.Value
iNum(2) = TextBox25.Value
iNum(3) = TextBox26.Value
TextBox8.Value = iNum(1) + iNum(2) + iNum(3)
'check article exists
Dim emptyRow As Long
Dim rcnt As Long
Dim i As Long
ActiveWorkbook.Sheets("existing").Activate
rcnt = Sheets("existing").Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To rcnt
If TextBox8.Text = Sheets("existing").Range("A" & i).Value Then
Application.DisplayAlerts = False
MsgBox "This already exists"
SendKeys "{ENTER}"
Application.DisplayAlerts = True
Exit Sub
End If
Next
Range("A1").Select
Do
If IsEmpty(ActiveCell) = False Then
ActiveCell.Offset(1, 0).Select
End If
Loop Until IsEmpty(ActiveCell) = True
ActiveCell.Value = TextBox8.Text
To remove the message Box all you need to do is delete the following lines in your code
Application.DisplayAlerts = False
MsgBox "This already exists"
SendKeys "{ENTER}"
Application.DisplayAlerts = True
I am not sure what the first part of the code is doing. if you could provide some example I can help with that. But I have rationalized the second part and this will now achieve what the original code was attempting to achieve with lesser lines.
'check article exists
Dim emptyRow As Long
Dim rcnt As Long
Dim i As Long
Dim varProdCode As Long
ActiveWorkbook.Sheets("existing").Activate
varProdCode = TextBox8.Text
rcnt = Sheets("existing").Range("A" & Rows.Count).End(xlUp).Row
Do Until varProdCode = 0
For i = 2 To rcnt
If varProdCode = Sheets("existing").Range("A" & i).Value Then
varProdCode = varProdCode + 1
Exit For
Else
Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Value = varProdCode
varProdCode = 0
Exit Sub
End If
Next
Loop
This is the code that works
Private Sub CommandButton2_Click()
With TextBox26
If myreset = True Then
.Tag = 0
myreset = False
End If
.Tag = Val(.Tag) + 1
.Value = VBA.Format(Val(.Tag), "0000")
End With
Dim emptyRow As Long
Dim rcnt As Long
Dim c As Long
rcnt = Sheets("existing").Range("A" & Rows.Count).End(xlUp).Row
For c = 2 To rcnt
Dim iNum(1 To 8) As String
iNum(1) = TextBox24.Value
iNum(2) = TextBox25.Value
iNum(3) = TextBox26.Value
'check if article exists
ActiveWorkbook.Sheets("existing").Activate
If Sheets("existing").Range("A" & c).Value = iNum(1) & iNum(2) & "-" & iNum(3) Then
TextBox26.Value = TextBox26.Value + 1
iNum(3) = TextBox26.Value
End If
Next c
'create article number
TextBox8.Value = iNum(1) + iNum(2) + "-" + iNum(3)
'select first column
Range("A1").Select

Error 1004 on VBA

I have five worksheet in all that are using the below code which is stored in a workbook. The first worksheet works perfectly well with the code. The second spreadsheet can check for the first item before returning the error. The subsequent third and fourth worksheet return the error immediately. The fifth worksheet on the other hand return error 400. May I know is my code the source of the problem or it's the checkbox because I copied and paste from the first worksheet.
Sub test5()
Dim MyFile As String
Dim FinalRow As Long
Dim Row As Long
Dim i As Integer
Dim d As Integer
d = 2
i = 0
FinalRow = Cells(Rows.count, "S").End(xlUp).Row
For Row = 3 To FinalRow
If Not IsEmpty(ActiveSheet.Cells(Row, "S")) Then
i = i + 1
d = d + 1
MyFile = ActiveSheet.Cells(Row, "S").Value
If Dir(MyFile) <> "" Then
ActiveSheet.OLEObjects("CheckBox" & i). _
Object.Value = True ' <~~~~~~~~~~~~~~~~ Error occurs here
With ActiveSheet.Cells(d, "F")
.Value = Now
.NumberFormat = "dd/mm/yy"
'If (ActiveSheet.Cells(d, "F") - ActiveSheet.Cells(d, "G") >= 0) Then
' ActiveSheet.Cells(d, "F").Font.Color = vbRed
'End If
If (.Value - .Offset(0, 1).Value) >= 0 Then
.Font.Color = vbRed
Else
.Font.Color = vbBlack
End If
End With
' i = i + 1
'd = d + 1
End If
End If
Next
End Sub
The program terminates after stepping into this line of code:
ActiveSheet.OLEObjects("CheckBox" & i). _ Object.Value = True
OLEObject does not have a member called value. If you are trying to display the OLEObject, use visible instead
ActiveSheet.OLEObjects("CheckBox" & i).Visible = True
See all OLEObject members here :
OLEObject Object Members