End If with out block If - error. [closed] - vb.net

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Hi I have a VB linking to my Excel sheet done by the previous IT guy. Now its showing error "End If without Block If". Please help me debug. Codes below. Thank you all.
Private EditingRow As String
Private gCurrentStatus As String
Private gLocation As String
Private gRack As String
Private Sub cboType_Change()
cboSerialNo.Clear
Application.ScreenUpdating = False
Sheets("SGS Cylinder List").Select
ActiveSheet.Unprotect
ActiveSheet.UsedRange.Select
Selection.Sort Key1:=Range("D1"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
Set rng = Columns("D")
txtTotalSelectedType.Value = WorksheetFunction.countIF(rng, cboType.Value)
''' List all the selected Serial No
firstRowfound = False
firstrow = 0
lastRow = 0
Range("D1").Select
Do Until ActiveCell.Value = ""
If (firstRowfound = False And Cells(ActiveCell.Row, 4).Value = cboType.Value) Then
'MsgBox "1st row =" & ActiveCell.Row
firstrow = ActiveCell.Row
firstRowfound = True
End If
If (firstRowfound) Then
cboSerialNo.AddItem Trim(Cells(ActiveCell.Row, 3).Value) & " ," & Trim(Cells(ActiveCell.Row, 11))
End If
If (firstRowfound And Cells(ActiveCell.Row + 1, 4).Value <> cboType.Value) Then
'MsgBox "last row =" & ActiveCell.Row
lastRow = ActiveCell.Row
lastRowFound = True
Exit Do
End If
ActiveCell.Offset(1, 0).Select
Loop
If (firstrow > 0) Then
Set rngSelectedStatus = Range("I" & firstrow & ":I" & lastRow)
txtTotalCylinderAvailable.Value = WorksheetFunction.countIF(rngSelectedStatus, "Available")
Else
txtTotalCylinderAvailable.Value = 0
End If
ActiveSheet.Protect
Application.ScreenUpdating = True
End Sub
Private Sub cmdAdvancedAnalysis_Click()
If cboType.Value = "" Then
Exit Sub
End If
Worksheets("SGS Cylinder List").Select
ActiveSheet.Unprotect
newAddr = Sheets("SGS Cylinder List").[A2].CurrentRegion.Address(ReferenceStyle:=xlR1C1)
Sheets("Advanced").PivotTableWizard SourceType:=xlDatabase, SourceData:="SGS Cylinder List!" & newAddr
Sheets("Advanced").PivotTables("PivotTable1").RefreshTable
' Filter the PivotTable with the new Cylinder Type
Sheets("Advanced").PivotTables("PivotTable1").PageFields("Type").CurrentPage = cboType.Value
End Sub
Private Sub cmdCreateCylinder_Click()
Dim form1 As frmCylinder
Set form1 = New frmCylinder
form1.Show
End Sub
Private Sub cmdDisposalDate_Click()
Dim form1 As frmSelectDate
Set form1 = New frmSelectDate
form1.Show
Me.txtRsltDisposalDate = form1.SelectedDate
End Sub
Private Sub cmdLastUpdate_Click()
Dim form1 As frmSelectDate
Set form1 = New frmSelectDate
form1.Show
Me.txtLastUpdate.Value = form1.SelectedDate
End Sub
Private Sub cmdSearch_Click()
Sheets("SGS Cylinder List").Select
Range("C2").Select
Debug.Print cboSerialNo.Value
If cboSerialNo.Value = "" Then
Exit Sub
End If
cmdUpdate.Enabled = True
Do Until ActiveCell.Value = ""
' Found the row contains this given Serial No
''' to check the cboSerialNo first
serialNo = Left(cboSerialNo.Value, InStr(cboSerialNo.Value, ",") - 2)
If CStr(ActiveCell.Value) = serialNo Then
EditingRow = ActiveCell.Row
ActiveCell.EntireRow.Select
''' Show Selection
' Populate Location List
cboLocation.Clear
Sheets("Location").Select
Range("A2").Select
Do Until ActiveCell.Value = ""
cboLocation.AddItem ActiveCell.Value
ActiveCell.Offset(1, 0).Select
If CStr(ActiveCell.Value) = serialNo Then
EditingRow = ActiveCell.Row
ActiveCell.EntireRow.Select
cboRack.Clear
Sheets("Location").Select
Range("B2").Select
Do Until ActiveCell.Value = ""
cboRack.AddItem ActiveCell.Value
ActiveCell.Offset(1, 0).Select
Loop
End If
Sheets("SGS Cylinder List").Select
If (Cells(ActiveCell.Row, 1).Value <> "") Then
cboLocation.Value = Cells(ActiveCell.Row, 1).Value
End If
If (Cells(ActiveCell.Row, 1).Value <> "") Then
cboRack.Value = Cells(ActiveCell.Row, 1).Value
End If
txtRsltClientName.Value = Cells(ActiveCell.Row, 5).Value
txtRsltWell.Value = Cells(ActiveCell.Row, 6).Value
txtRsltJobID.Value = Cells(ActiveCell.Row, 7).Value
''' Populate Sample Type List
cboRsltSampleType.Clear
Set sampleTypeList = Range("SampleTypes")
For Each cell In sampleTypeList
cboRsltSampleType.AddItem cell.Value
Next
If (Cells(ActiveCell.Row, 8).Value <> "") Then
cboRsltSampleType.Value = Cells(ActiveCell.Row, 8).Value
End If
txtRsltDisposalDate.Value = Cells(ActiveCell.Row, 9).Value
' Set Existing Cylinder Status
cboRsltCylinderStatus.Clear
Set statusList = Range("StatusTypes")
For Each cell In statusList
cboRsltCylinderStatus.AddItem cell.Value
Next
If (Cells(ActiveCell.Row, 10).Value <> "") Then
cboRsltCylinderStatus.Value = Cells(ActiveCell.Row, 10).Value
End If
''' Save Current Row of Cylinder Data to Global variables
gLocation = Cells(ActiveCell.Row, 1).Value
gRack = Cells(ActiveCell.Row, 2).Value
gClientName = Cells(ActiveCell.Row, 5).Value
gWell = Cells(ActiveCell.Row, 6).Value
gJobID = Cells(ActiveCell.Row, 7).Value
gSampleType = Cells(ActiveCell.Row, 8).Value
gCurrentStatus = Cells(ActiveCell.Row, 10).Value
Exit Sub
End If
ActiveCell.Offset(1, 0).Select
Loop
End Sub
Private Sub cmdUpdate_Click()
''' 1. Save the current setting to a History Sheet if found changes made
''' 2. Update the current row
'' if any property of the Cylinder change
If ((gCurrentStatus <> cboRsltCylinderStatus.Value _
Or gLocation <> cboLocation.Value _
Or gWell <> txtRsltWell.Value _
Or gJobID <> txtRsltJobID.Value _
Or gSampleType <> cboRsltSampleType.Value) _
And EditingRow <> "") Then
Range("LastUpdateDate").Value = Date
Sheets("SGS Cylinder List").Select
ActiveSheet.Unprotect
' Copy that edited range
Range("A" & EditingRow & ":I" & EditingRow).Select
Selection.Copy
'' Check if Cylinder Status change
If gCurrentStatus <> cboRsltCylinderStatus.Value Then
Sheets("History List").Select
Range("A" & ActiveSheet.Rows.Count).End(xlUp).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
' Add a Current Status
Cells(ActiveCell.Row, 10).Value = cboRsltCylinderStatus.Value
' Add a Modified Date
If txtLastUpdate = "" Then
txtLastUpdate = Date
End If
Cells(ActiveCell.Row, 11).Value = txtLastUpdate
Cells(ActiveCell.Row, 11).NumberFormat = "dd-mmm-yy"
''' End of Step 1
End If
''' Start updating new changes
Sheets("SGS Cylinder List").Select
''' Add a New Location
If (txtRsltLocation.Value <> "" And cboLocation.Value = "") Then
Sheets("Location").Select
Range("A" & ActiveSheet.Rows.Count).End(xlUp).Select
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = txtRsltLocation.Value
Sheets("SGS Cylinder List").Select
Cells(EditingRow, 1).Value = txtRsltLocation.Value
Else
Cells(EditingRow, 1).Value = cboLocation.Value
End If
Cells(EditingRow, 5).Value = txtRsltClientName.Value
Cells(EditingRow, 6).Value = txtRsltWell.Value
Cells(EditingRow, 7).Value = txtRsltJobID.Value
Cells(EditingRow, 8).Value = cboRsltSampleType.Value
Cells(EditingRow, 9).Value = txtRsltDisposalDate.Value
Cells(EditingRow, 10).Value = cboRsltCylinderStatus.Value
End If
''' Reset
cboRsltCylinderStatus.Value = ""
cboLocation.Value = ""
txtRsltClientName.Value = ""
txtRsltWell.Value = ""
txtRsltJobID.Value = ""
cboRsltSampleType.Value = ""
txtRsltDisposalDate.Value = ""
cboRsltCylinderStatus.Value = ""
End Sub
Private Sub ComboBox1_Change()
End Sub
Private Sub UserForm_Initialize()
Set typeList = Range("CylinderTypes")
For Each cell In typeList
cboType.AddItem cell.Value
Next
End Sub
Any help is much appreciated. Thank you

End If
ActiveCell.Offset(1, 0).Select
Loop
The End If at the beginning there is the cause of the error because it doesn't correspond to an opening If statement. Did you mean to put an Else If earlier in your code?
Update: I see this code:
Do Until ActiveCell.Value = ""
cboLocation.AddItem ActiveCell.Value
ActiveCell.Offset(1, 0).Select
There is no corresponding Loop keyword, and it's in the same scope as the End If I mentioned above, it's possible this is throwing the VBA interpreter/compiler off, but don't you have any detailed error messages with line-numbers or anything?

I think it's here .. in your Private Sub cmdSearch_Click()
cboLocation.Clear
Sheets("Location").Select
Range("A2").Select
Do Until ActiveCell.Value = "" '-------> You dont have 'Loop'

Related

How do i get to next form in visual basic

I am trying to get to the next form for my excel macro
right now I have a login form that has user name and password
that works when I press login it goes to next form.
but when I go to my next form and type the information in it it closes and doesn't pull up the next forum.
Can someone please explain to me what I am doing wrong? why wont my next form pop up?
Private Sub cmdAdd_Click()
'Dim iRow As Long
'Dim ws As Worksheet
Set ws = Worksheets("D544 Back Panel")
'find first empty row in database
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
'check for a part number
If Trim(Me.txtPrd.Value) = "" Then
Me.txtPrd.SetFocus
MsgBox "Please enter a Production Number"
Exit Sub
End If
'copy the data to the database
'use protect and unprotect lines,
' with your password
' if worksheet is protected
With ws
' .Unprotect Password:="Password"
.Cells(iRow, 1).Value = Me.txtDate.Value
.Cells(iRow, 2).Value = Me.txtHrs.Value
.Cells(iRow, 3).Value = Me.txtPrd.Value
.Cells(iRow, 4).Value = Me.txtSrp.Value
.Cells(iRow, 5).Value = Me.txtOper.Value
' .Protect Password:="Password"
End With
'clear the data
Me.txtDate.Value = ""
Me.txtHrs.Value = ""
Me.txtPrd.Value = ""
Me.txtSrp.Value = ""
Me.txtOper.Value = ""
Me.txtPrd.SetFocus
Unload Me
End Sub
Private Sub cmdSubmit_Click()
'Dim iRow As Long
'Dim ws As Worksheet
Set ws = Worksheets("Scrap")
'find first empty row in database
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
'check for a part number
If Trim(Me.txtPress.Value) = "" Then
Me.txtPress.SetFocus
MsgBox "Please enter press scrap"
Exit Sub
End If
'copy the data to the database
'use protect and unprotect lines,
' with your password
' if worksheet is protected
With ws
' .Unprotect Password:="Password"
.Cells(iRow, 1).Value = Me.txtDelam.Value
.Cells(iRow, 2).Value = Me.txtCuts.Value
.Cells(iRow, 3).Value = Me.txtBurns.Value
.Cells(iRow, 4).Value = Me.txtDents.Value
.Cells(iRow, 5).Value = Me.txtStaple.Value
.Cells(iRow, 6).Value = Me.txtGlue.Value
.Cells(iRow, 7).Value = Me.txtPress.Value
' .Protect Password:="Password"
End With
'clear the data
Me.txtDelam.Value = ""
Me.txtCuts.Value = ""
Me.txtBurns.Value = ""
Me.txtDents.Value = ""
Me.txtStaple.Value = ""
Me.txtGlue.Value = ""
Me.txtPress.Value = ""
Me.txtPress.SetFocus
Unload Me
End Sub
I used
Formname1.Hide
Formname2.Show
This seemed to solve my issue. Thanks for the help guys. Sorry I am very new to this site.

Statement to create excel vba hyperlink throws Run-time '1004' Error

So I have had a couple of questions I've asked regarding excel VBA, and I appreciate you all bearing with me as I stumble through learning about all this. Your answers have been a tremendous help and learning experience.
So far, I have a subroutine whose main responsibility is to write all of the values collected through a user form with various validations and dynamic comboboxes. My final task is to get this Subroutine to assign a hyperlink to the location selected by an earlier loop. But with my current syntax, I'm getting a "run-time error '1004' method '_default' of object 'range' failed". Some research proved that the cell coordinates require a .address property after them in order to avert this error, but it did not resolve the issue. The code is below:
Option Explicit
Dim cnt As Integer
Dim i As Long, rowOff As Long
Dim dateSel As String
Dim timeSel As String
Dim branch As String
Dim sht As Worksheet
Dim cel As Range
Dim matchingHeader As Range
Public Sub UserForm_Initialize()
'clear form
BranchBox.Value = ""
DateBox.Value = ""
TimeBox.Value = ""
'populate sheet names from each branch
For Each sht In ActiveWorkbook.Sheets
If sht.Name = "ApplicantInfo" Then
'Do Nothing
Else
Me.BranchBox.AddItem sht.Name
End If
Next sht
End Sub
Public Sub HoldButton_Click() 'revisit... throwing Time message box regardless what's selected
If TimeBox.Value <> "" Then
If DateBox.Value <> "" Then
If BranchBox.Value <> "" Then
sht.Cells(rowOff, i).Value = "-"
'Save workbook
Else
MsgBox "You must select a branch for your appointment"
End If
Else
MsgBox "You must select a date for your appointment"
End If
Else
MsgBox "You must select a time for your appointment"
End If
End Sub
Private Sub ResetButton_Click()
FirstName.Value = ""
LastName.Value = ""
EMail.Value = ""
Phone.Value = ""
Skills.Value = ""
'BranchBox.Value = "" throws error
DateBox.Value = ""
TimeBox.Value = ""
End Sub
Private Sub ScheduleButton_Click()
Dim row As Long, column As Long
Dim linkDisplay As String
'test for RowOff and i <> 0
If IsNull(BranchBox) = True Then
MsgBox "Select a branch for you interview before you click schedule"
Else
If IsNull(DateBox) = True Then
MsgBox "Select a date for you interview before you click schedule"
Else
If IsNull(TimeBox) = True Then
MsgBox "Select a time for you interview before you click schedule"
Else
'find first empty row in applicant profile tab.
'Insert applicant information in free row
'parse applicant name as a link to found free row above
'replace "-" placeholder for held appointment with applicant name as a link
Call GetFirstEmptyRow
'write selected values into row
Dim InfoRow As Integer
InfoRow = ActiveCell.row
ActiveCell.Value = ActiveCell.Offset(-5, 0).Value + 5
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = LastName.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = FirstName.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = EMail.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Phone.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Skills.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = BranchBox.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = DateBox.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = TimeBox.Value
branch = BranchBox.Value
Set sht = ActiveWorkbook.Worksheets(branch)
dateSel = DateBox.Value
timeSel = TimeBox.Value
'scan for selected date
For i = 2 To sht.Rows.Count
Set cel = sht.Cells(i, 1)
If cel.Value = dateSel Then
column = i
Exit For
End If
Next i
'Scan for selected time
For i = 2 To sht.Columns.Count
Set cel = sht.Cells(1, i)
If CStr(cel.Value) = timeSel Then
row = i
Exit For
End If
Next i
linkDisplay = LastName.Value & ", " & FirstName.Value
'This is the error
sht.Hyperlinks.Add Anchor:=sht.Cells(row, column).Address, Address:="", SubAddress:=ActiveWorkbook.Worksheets("ApplicantInfo").Cells(InfoRow, 1).Address, TextToDisplay:=linkDisplay
'end of validations
End If
End If
End If
End Sub
Public Sub GetFirstEmptyRow()
Set sht = ActiveWorkbook.Worksheets("ApplicantInfo")
sht.Activate
Range("A1").Select
Do
If IsEmpty(ActiveCell) = False Then
ActiveCell.Offset(1, 0).Select
End If
Loop Until IsEmpty(ActiveCell) = True
End Sub
Public Sub Save()
End Sub
Public Sub TimeBox_Change()
End Sub
Public Sub BranchBox_Change()
'clear Date Box Values
For i = DateBox.ListCount - 1 To 0 Step -1
DateBox.RemoveItem i
Next i
'clear Time Box Values
i = 0
For i = TimeBox.ListCount - 1 To 0 Step -1
TimeBox.RemoveItem i
Next i
'reset i to 0
i = 0
'populate dates
Me.DateBox.List = Worksheets(BranchBox.Value).Range("A2:A31").Value
End Sub
Public Sub DateBox_Change()
branch = BranchBox.Value
Set sht = ActiveWorkbook.Worksheets(branch)
dateSel = DateBox.Value
'Get Row to scan
For i = 2 To sht.Rows.Count
Set cel = sht.Cells(i, 1)
If cel.Value = dateSel Then
rowOff = i
Exit For
End If
Next i
'Scan selected row for blank cells
For i = 2 To sht.Columns.Count
Set cel = sht.Cells(rowOff, i)
If CStr(cel.Value) = "" Then
Set matchingHeader = sht.Cells(1, i)
TimeBox.AddItem matchingHeader.Text
End If
Next i
Me.TimeBox.AddItem ("No Appointments Available")
End Sub
This is the line which errors:
sht.Hyperlinks.Add Anchor:=sht.Cells(row, column).Address, _
Address:="", _
SubAddress:=ActiveWorkbook.Worksheets("ApplicantInfo") _
.Cells(InfoRow, 1).Address, _
TextToDisplay:=linkDisplay
Help is much appreciated! Thanks in advance!
sht.Hyperlinks.Add Anchor:=sht.Cells(row, column), _
Address:="", _
SubAddress:="'ApplicantInfo'!" & Cells(InfoRow, 1).Address(False, False), _
TextToDisplay:=linkDisplay
I'd typically use a utility method for this type of thing though.
E.g. something like:
Sub CreateHyperlink(FromCell As Range, ToCell As Range, Optional LinkText As String = "")
Dim subAddr, txt
subAddr = ToCell.Address(False, False)
If FromCell.Worksheet.Name <> ToCell.Worksheet.Name Then
subAddr = "'" & ToCell.Worksheet.Name & "'!" & subAddr
End If
txt = IIf(LinkText <> "", LinkText, FromCell.Value)
If Len(txt) = 0 Then txt = "Go"
With FromCell.Worksheet
.Hyperlinks.Add Anchor:=FromCell, Address:="", _
SubAddress:=subAddr, TextToDisplay:=txt
End With
End Sub

VBA Runtime Error 9 - Subscript out of range

I am attempting to create a user form that will propagate the first available row of the excel sheet with information. I am struggling to get the range correct, and the form is currently showing 'Subscript out of range' ; 'Runtime error 9'. There also seems to be a problem with the 'if' statement, but following the standard advice online doesn't seem to have helped solve the problem.
If anyone has any idea where I'm going wrong (I'm very new to this) that would be great.
Private Sub UserForm_Initialize()
BusinessAreaBox.List = Array("option one", "option two")
End Sub
Private Sub CommandButton1_Click()
Dim RowCount As Long
RowCount = Sheets("Sheet1").Range.Sheets("Sheet1").Cells(2, "A")
With ThisWorkbook.Sheets("Sheet1").Range("A2")
.Offset(RowCount, 0).Value = BusinessArea1.Value
.Offset(RowCount, 1).Value = BusinessContact1.Value
.Offset(RowCount, 2).Value = LPSContact1.Value
.Offset(RowCount, 4).Value = ProjectedFTE1.Value
.Offset(RowCount, 5).Value = DateOfMostRecentMeeting1.Value
.Offset(RowCount, 6).Value = FTEComment1.Value
.Offset(RowCount, 7).Value = ProposedMove1.Value
.Offset(RowCount, 8).Value = DeskUtilisation1.Value
.Offset(RowCount, 9).Value = OtherComment1.Value
.Offset(RowCount, 10).Value = Actions1.Value
If RegularMeeting1.Value = True Then
.Offset(RowCount, 3).Value = "Yes"
Else
.Offset(RowCount, 3).Value = "No"
End If
RegularMeeting1.Value = True Or False
End With
End Sub
Private Sub CommandButton2_Click()
Unload Me
End Sub
I guess you may be after this
Private Sub CommandButton1_Click()
With ThisWorkbook.Sheets("Sheet1")
.Cells(.Rows.Count, 1).End(xlUp).Offset(1).Resize(, 11).Value = Array(BusinessArea1.Value, _
BusinessContact1.Value, _
LPSContact1.Value, _
IIf(RegularMeeting1.Value, "Yes", "No"), _
ProjectedFTE1.Value, _
DateOfMostRecentMeeting1.Value, _
FTEComment1.Value, _
ProposedMove1.Value, _
DeskUtilisation1.Value, _
OtherComment1.Value, _
Actions1.Value)
End With
RegularMeeting1.Value = True Or False '<--| what is this supposed to do?
End Sub
Try writing to the cells this way. You need to active the sheet and cell first.
Dim myArr As Variant
myArr = Array(BusinessArea1.Value, _
LPSContact1.Value, _
ProjectedFTE1.Value, _
DateOfMostRecentMeeting1.Value, _
FTEComment1.Value, _
ProposedMove1.Value, _
DeskUtilisation1.Value, _
OtherComment1.Value, _
Actions1.Value)
sheet1.activate
sheet1.range("A2").activate
for I = 0 to ubound(myArr)
activecell.value = myArr(I)
activecell.Offset(1,0).activate
Next I

VBA Programming. Error or Prompt will appear in Userform if field in sheet already has content

I wanted to have a code wherein there will be an error or prompt in the userform if the cell in the sheet- wherein the data will be transferred, already has content. As of now, the code I'm using doesn't show any prompt but it succeeds in not updating the cell if a data is to be transferred to it again.
Private Sub CancelButton_Click()
Unload Me
End Sub
Private Sub ClearButton_Click()
Call UserForm_Initialize
End Sub
Private Sub OKButton_Click()
Dim emptyRow As Long
'Make Sheet1 active
Sheet1.Activate
'Determine emptyRow
Dim rFound As Range: Set rFound = Range("B:B").Find(BarcodeTextBox.Value, , , xlWhole)
If rFound Is Nothing Then
emptyRow = Range("B" & Rows.Count).End(xlUp).Row + 1
Else
emptyRow = rFound.Row
End If
'Transfer information
If TimeOptionButton1.Value = True Then
Cells(emptyRow, 5).Value = "Yes"
End If
If TimeOptionButton2.Value = True Then
Cells(emptyRow, 7).Value = "Yes"
End If
If BreakOptionButton1.Value = True Then
Cells(emptyRow, 9).Value = "Yes"
End If
If BreakOptionButton2.Value = True Then
Cells(emptyRow, 11).Value = "Yes"
End If
If BreakOptionButton3.Value = True Then
Cells(emptyRow, 14).Value = "Yes"
End If
If BreakOptionButton4.Value = True Then
Cells(emptyRow, 16).Value = "Yes"
End If
Cells(emptyRow, 2).Value = BarcodeTextBox.Value
Set ws = ActiveSheet
Me.TextBox1 = Application.WorksheetFunction. _
CountIf(ws.Range("$T$2:$E$977"), "IN")
Me.TextBox2 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "LF")
Me.TextBox3 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "READYMAN")
Me.TextBox4 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "B-MIRK")
Me.TextBox5 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "VISITOR")
End Sub
Private Sub UserForm_Initialize()
'Set Time In as default
TimeOptionButton1.Value = True
'Empty BarcodeTextBox
BarcodeTextBox.Value = ""
Set ws = ActiveSheet
Me.TextBox1 = Application.WorksheetFunction. _
CountIf(ws.Range("$T$2:$E$977"), "IN")
Me.TextBox2 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "LF")
Me.TextBox3 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "READYMAN")
Me.TextBox4 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "B-MIRK")
Me.TextBox5 = Application.WorksheetFunction. _
CountIf(ws.Range("$U$2:$U$977"), "VISITOR")
End Sub
Thank you in advance!
Concerning your code, I think that you may add something like this:
If TimeOptionButton1.Value = True Then
if len(cells(emptyRow,5)) = 0 then
MsgBox "Write Error Message here"
else
Cells(emptyRow, 5).Value = "Yes"
end if
End If
For each yes. You may consider building a separate function/sub later to avoid repetition.

excel vba code corrupting my file consistently after a few runs

I have a relatively long set of subs that get run on a list of my excel files a few times a day. after a few runs, the file then becomes corrupted which normally would not be an issue b/c it doesn't really effect any of the data. however, I have another program that opens up each of the excel and pulls some key data from each one to make a summary sheet. because the corrupted file gives a message that says something along the lines of "there is a problem with some of your content" the summary program stops with a
run-time error '1004': Method of object 'Workbooks' Failed
I can not for the life of me figure out what in my code is causing the corruption. Is there a way I can have the summary code ignore the corruption notification? Ive tried a handful of different things including turning the application notifications off in my code to no avail.
Any help is greatly appreciated! ill post my all my code with a brief description below:
Here is the code from the summary file that opens each of the
individual files and pulls data:
Sub OEEsummmary()
Dim ActCycCell, ExpCycCell, ExpCurCycCell, ShiftCell, DifCell, DownCell, DTResACell, DTResBCell, PartCell, OpNamCell, OprCell, RejCell, RejResCell As Range
Dim MySheet As Worksheet
Dim Txt$, MyPath$, MyWB$
Dim myValue As Integer
Dim x As Long
Dim v As Variant, r As Range, rWhere As Range
MyPath = "L:\Manufacturing Engineering\Samuel Hatcher\"
x = 2
Set MySheet = ActiveSheet
'Application.ScreenUpdating = False
Application.EnableEvents = False
MySheet.Range("B2:G18").ClearContents
MySheet.Range("J2:O18").ClearContents
Do While MySheet.Range("A" & x).Value <> ""
MyWB = MySheet.Range("A" & x).Text
Workbooks.Open Filename:=MyPath & MyWB, ReadOnly:=True, IgnoreReadOnlyRecommended:=True
Set ActCycCell = ActiveSheet.Range("E21")
Set ExpCycCell = ActiveSheet.Range("D21")
Set ShiftCell = ActiveSheet.Range("E2")
Set DownCell = ActiveSheet.Range("K28")
Set DTResACell = ActiveWorkbook.Worksheets("Downtime").Range("O9")
Set DTResBCell = ActiveWorkbook.Worksheets("Downtime").Range("O10")
Set PartCell = ActiveSheet.Range("E4")
Set ExpCurCycCell = ActiveSheet.Range("D22")
If ActiveSheet.Range("I3") = "" Then
Set OpNamCell = ActiveSheet.Range("I2")
Else
Set OpNamCell = ActiveSheet.Range("I3")
End If
Set OprCell = ActiveSheet.Range("C4")
Set RejCell = ActiveSheet.Range("H21")
Set RejResCell = ActiveWorkbook.Worksheets("Rejected Parts").Range("H5")
With MySheet.Range("A" & x)
.Offset(0, 14).Value = OprCell.Value
.Offset(0, 13).Value = OpNamCell.Value
.Offset(0, 12).Value = PartCell.Value
.Offset(0, 11).Value = ShiftCell.Value
.Offset(0, 10).Value = RejResCell.Value
.Offset(0, 9).Value = RejCell.Value
.Offset(0, 6).Value = ActCycCell.Value
.Offset(0, 5).Value = ExpCycCell.Value
.Offset(0, 4).Value = ExpCurCycCell.Value
.Offset(0, 3).Value = DTResBCell.Value
.Offset(0, 2).Value = DTResACell.Value
.Offset(0, 1).Value = DownCell.Value
End With
ActiveWorkbook.Close savechanges:=False
x = x + 1
Loop
Call sort
'Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Clears the page of data to prepare it for a new shift of entering
data:
Sub ClearFrontEnd()
Sheets("Front End").Unprotect ("29745")
'prompts user to confirm if they realy want to clear entry
response = MsgBox("Are You Sure?", vbYesNo)
If response = vbNo Then
Exit Sub
End If
'checks to see if operator number is there
If range("I3").Value = "" Then
MsgBox "ENTER OPORATOR # AND CLICK NEW SHIFT AGAIN"
Else
Call StopTimer
Call prodChoose
Call transfer
Application.ScreenUpdating = False
ActiveWorkbook.Save
Sheets("Front End").Unprotect ("29745")
Sheets("Front End").Select
'Deletes the data from the entry and unique key fields
range("E8:E20").ClearContents
range("I8:I27").ClearContents
range("J8:J27").ClearContents
range("K8:K27").ClearContents
range("I3").ClearContents
range("H8").Value = ""
range("H9").Value = ""
range("H10").Value = ""
range("H11").Value = ""
range("H12").Value = ""
range("H13").Value = ""
range("H14").Value = ""
range("H15").Value = ""
range("H16").Value = ""
range("H17").Value = ""
range("H18").Value = ""
range("H19").Value = ""
range("H20").Value = ""
range("A1").Select
MsgBox "Please enter the correct values for SHIFT #, SHIFT LENGTH, PART #, AND OPORATOR #, Thanks! Have a great day!!"
End If
Sheets("Front End").Protect ("29745")
Call timerchoose
Application.ScreenUpdating = True
End Sub
This copies the data from the front page to a raw data sheet every
hour:
Sub transfer()
Sheets("Front End").Unprotect ("29745")
Application.ScreenUpdating = False
Dim x As Long
Dim v As Variant, r As range, rWhere As range
'set starting point at row 8
x = 8
'defines the sheet the data is being coppied from and pasted to
Dim sourceSheet As Worksheet: Set sourceSheet = ThisWorkbook.Worksheets("Front End")
Dim destSheet As Worksheet: Set destSheet = ThisWorkbook.Worksheets("Raw Data")
If sourceSheet.range("I3").Value = "" Then
Call StartTimer
Exit Sub
Else
Do While range("L" & x).Value <> ""
'Checks if the unique code is in the raw data sheet or not
v = sourceSheet.range("M" & x).Value
Set rWhere = destSheet.range("S:S")
Set r = rWhere.Find(what:=v, After:=rWhere(1))
If r Is Nothing Then
'selects the next row where the 1st column is empty
lMaxRows = destSheet.Cells(destSheet.Rows.Count, "A").End(xlUp).Row
'pastes the data from the specified cells into the next empty row
destSheet.range("A" & lMaxRows + 1).Value = sourceSheet.range("C2").Value
destSheet.range("M" & lMaxRows + 1).Value = sourceSheet.range("E2").Value
destSheet.range("N" & lMaxRows + 1).Value = sourceSheet.range("E4").Value
destSheet.range("P" & lMaxRows + 1).Value = sourceSheet.range("G4").Value
destSheet.range("Q" & lMaxRows + 1).Value = sourceSheet.range("C4").Value
destSheet.range("O" & lMaxRows + 1).Value = sourceSheet.range("I3").Value
destSheet.range("B" & lMaxRows + 1).Value = sourceSheet.range("J" & x).Value
destSheet.range("C" & lMaxRows + 1).Value = sourceSheet.range("K" & x).Value
destSheet.range("D" & lMaxRows + 1).Value = sourceSheet.range("L" & x).Value
destSheet.range("E" & lMaxRows + 1).Value = sourceSheet.range("I" & x).Value
destSheet.range("S" & lMaxRows + 1).Value = sourceSheet.range("M" & x).Value
x = x + 1
Else
x = x + 1
End If
Loop
x = 8
Do While range("D" & x).Value <> 0
If range("E" & x).Value <> "" Then
'Checks if the unique code is in the raw data sheet or not
v = sourceSheet.range("A" & x).Value
Set rWhere = destSheet.range("S:S")
Set r = rWhere.Find(what:=v, After:=rWhere(1))
If r Is Nothing Then
'selects the next row where the 1st column is empty
lMaxRows = destSheet.Cells(destSheet.Rows.Count, "A").End(xlUp).Row
'pastes the data from the specified cells into the next empty row
destSheet.range("A" & lMaxRows + 1).Value = sourceSheet.range("C2").Value
destSheet.range("M" & lMaxRows + 1).Value = sourceSheet.range("E2").Value
destSheet.range("N" & lMaxRows + 1).Value = sourceSheet.range("E4").Value
destSheet.range("P" & lMaxRows + 1).Value = sourceSheet.range("G4").Value
destSheet.range("Q" & lMaxRows + 1).Value = sourceSheet.range("C4").Value
destSheet.range("O" & lMaxRows + 1).Value = sourceSheet.range("I3").Value
destSheet.range("B" & lMaxRows + 1).Value = sourceSheet.range("B" & x).Value
destSheet.range("L" & lMaxRows + 1).Value = sourceSheet.range("C" & x).Value
destSheet.range("F" & lMaxRows + 1).Value = sourceSheet.range("D" & x).Value
destSheet.range("G" & lMaxRows + 1).Value = sourceSheet.range("E" & x).Value
destSheet.range("I" & lMaxRows + 1).Value = sourceSheet.range("G" & x).Value
destSheet.range("K" & lMaxRows + 1).Value = sourceSheet.range("H" & x).Value
destSheet.range("H" & lMaxRows + 1).Value = sourceSheet.range("N" & x).Value
destSheet.range("J" & lMaxRows + 1).Value = sourceSheet.range("O" & x).Value
destSheet.range("S" & lMaxRows + 1).Value = sourceSheet.range("A" & x).Value
x = x + 1
Else
x = x + 1
End If
Else
x = x + 1
End If
Loop
'sorts Raw Data table after new data is added
Dim ws As Worksheet
Set ws = ActiveWorkbook.Worksheets("Raw Data")
'specifies how to sort the data
With ws.Sort.SortFields
.Clear
.add Key:=ws.range("A2:A" & lMaxRows + 1), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
.add Key:=ws.range("B2:B" & lMaxRows + 1), SortOn:=xlSortOnValues, _
Order:=xlAscending, DataOption:=xlSortNormal
'specifies range over which to sort
End With
With ws.Sort
.SetRange ws.range("A1:S" & lMaxRows + 1)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End If
Sheets("Front End").Protect ("29745")
Call SortDTWeek
Call SortDTMonth
Call StartTimer
Application.ScreenUpdating = True
End Sub
This checks a few cells constantly to see if they have been double
clicked, if so it puts the current time in that cell
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As range, cancel As Boolean)
'Adds downtime start and finish values
'Check to see if the click/selected cell is in columns I or J
If Not Intersect(Target, range("J:K")) Is Nothing Then
'Make sure cell is in range
If Target.Row > 7 And Target.Row <= 27 Then
'Update the value
Target.Value = Time()
End If
End If
End Sub
Checks to see if a set of cells has been changed, if so it puts the
now() value in a corresponding "key" column
Private Sub Worksheet_Change(ByVal Target As range)
Sheets("Front End").Unprotect ("29745")
Dim cell As range
'Adds unique keyA values
'Check to see if the changed cell is in column E
If Not Intersect(Target, range("E:E")) Is Nothing Then
For Each cell In Target.Cells
If cell.Value <> vbNullString And Target.Row > 7 And Target.Row <= 20 Then
'Update the "KeyA" value
Sheets("Front End").range("A" & Target.Row).Value = Now()
End If
Next cell
Else
'Adds unique keyB values
'Check to see if the changed cell is in column K
If Not Intersect(Target, range("K:K")) Is Nothing Then
For Each cell In Target.Cells
If cell.Value <> vbNullString And (Target.Row > "6" And Target.Row <= "27") Then
'Update the "KeyM" value
range("M" & Target.Row).Value = Now()
End If
Next cell
End If
End If
Sheets("Front End").Unprotect ("29745")
End Sub
thanks for any input this issue has been driving me crazy
as #MLind suggested in the comments, to bypass the corrupted file error and pull some data out i added this to my code:
Workbooks.Open Filename:=MyPath & MyWB, ReadOnly:=True, IgnoreReadOnlyRecommended:=True,
CorruptLoad:=xlExtractData
and used
Application.DisplayAlerts = False
within the loop to prevent any pop up boxes from stopping the sub