Autofill method of range class failed - help needed for my code - vba

I've been trying to make this work. It worked fine on my x64 version of office but not the x86 on my colleagues' computers. Can anyone gimme a fix please?
The VBA engine highlighted Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients) as the cause
Private Sub Check_Cases_Click()
Dim NoOfClients As Long
Application.DisplayAlerts = False
CO_Select = Application.InputBox("Please input the name of caseworker you would like to check on.", "Caseworker Name")
Range("A2").value = CO_Select
Application.ScreenUpdating = False
NoOfClients = Range("C2").value
CO_Name = Range("A2").value
CheckCaseMsg = MsgBox(CO_Name & ", there are " & NoOfClients & " clients under your name." & vbNewLine & vbNewLine & _
"System will now calculate all your active cases and display " & vbNewLine & _
"all the clients for your information." & vbNewLine & vbNewLine & _
"Confirm?", vbYesNo, "Case Checking")
If CheckCaseMsg = vbNo Then
Exit Sub
End If
If CheckCaseMsg = vbYes Then
'Remove the filters if one exists
'=========================================
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If
Clear
Startup_Formula
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients)
Application.Calculation = xlCalculationAutomatic
Range("GI_Table[[#All],[Client number]]").Copy
Range("GI_Table[[#All],[Client number]]").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.ScreenUpdating = True
ActiveSheet.ListObjects("GI_Table").Range.AutoFilter Field:=2, Criteria1:= _
Array("ACTIVE", "INACTIVE", "RENEWED"), Operator:=xlFilterValues
GI_CustomSort
GI_CustomSort
MsgBox "Case Checking Ready", vbInformation, "Ready"
End If
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Instead of just Range(".."). you should try
Dim sht as Worksheet
Set sht = Worksheets("Name")
sht.Range("..")
and so on.

You will get the Autofill method of range class failed error if the value of NoOfClients is 5. The end row is the same as the start row. Here is a simple way to reproduce the error.
Sub Sample()
NoOfClients = 5
Range("AV5").AutoFill Destination:=Range("AV5:AV" & NoOfClients)
End Sub
An alternative to .Autofill is to directly write to the range. For ex:
Range("AV5:AV" & NoOfClients).Formula = Range("AV5").Formula

Ok I know what's the problem now, I think.
I limited my scroll area in the Sub for Worksheet_Activate and the value of NoOfClients exceeded the allowed amount!
So I deleted that and I think it's ok now! This is my final code (with the scroll area becoming dynamic now)
Private Sub Check_Cases_Click()
Dim NoOfClients As Long
ActiveSheet.ScrollArea = ""
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = False
CO_Select = Application.InputBox("Please input the name of caseworker you would like to check on.", "Caseworker Name")
Range("A2").value = CO_Select
Application.ScreenUpdating = False
NoOfClients = Range("C2").value
CO_Name = Range("A2").value
CheckCaseMsg = MsgBox(CO_Name & ", there are " & NoOfClients & " clients under your name." & vbNewLine & vbNewLine & _
"System will now calculate all your active cases and display " & vbNewLine & _
"all the clients for your information." & vbNewLine & vbNewLine & _
"Confirm?", vbYesNo, "Case Checking")
If CheckCaseMsg = vbNo Then
Exit Sub
End If
If CheckCaseMsg = vbYes Then
'Remove the filters if one exists
'=========================================
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If
Clear
Startup_Formula
'Fill down the formula for n times where n= No of Clients of the Caseworker'
'=============================================================================
Dim Sht As Worksheet
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set Sht = Worksheets("Grand Info Sheet")
NoOfClients = Range("C2").value
NoOfClientsAdjusted = NoOfClients + 4
Sht.Range("AV5").AutoFill Destination:=Sht.Range("AV5:AV" & NoOfClientsAdjusted)
Application.Calculation = xlCalculationAutomatic
Range("GI_Table[[#All],[Client number]]").Copy
Range("GI_Table[[#All],[Client number]]").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.ScreenUpdating = True
GI_CustomSort
MsgBox "Case Checking Ready", vbInformation, "Ready"
Range("A1").Select
End If
ActiveSheet.ScrollArea = "A1:AW" & NoOfClientsAdjusted + 5
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Related

stop save changes if multiple conditions not met excel vba

I'm new in vba, i've been spending time and time surfing on internet trying to find solution but i could'nt
can someone assist on the below code, i want excel to force users to inter data in column K L and S whenever column B filled in with data (i.e column B is not empty) before save it.
may i know what i've missed below to make it run?!
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Set rng = Worksheets("Sheet1").Range("B7:B10000")
Application.ScreenUpdating = False
For Each cell In rng
If Not IsEmpty(cell) And IsEmpty(cell.Offset(-1, 9)) Then
Application.Goto cell.Offset(-1, 9)
Cancel = True
MsgBox "Save is cancelled!" & _
vbNewLine & "" & vbNewLine & "Please fill in cells in column K."
End If
Next
Application.ScreenUpdating = True
End Sub
Private Sub column_L()
Set rng = Worksheets("Sheet1").Range("B7:B10000")
Application.ScreenUpdating = False
For Each cell In rng
If Not IsEmpty(cell) And IsEmpty(cell.Offset(-1, 10)) Then
Application.Goto cell.Offset(-1, 10)
Cancel = True
MsgBox "Save is cancelled!" & vbNewLine & "" & vbNewLine & "Please fill in cells in column L."
End If
Next
Application.run macro:="column_L"
End Sub
Private Sub column_S()
Set rng = Worksheets("Sheet1").Range("B7:B10000")
Application.ScreenUpdating = False
For Each cell In rng
If Not IsEmpty(cell) And IsEmpty(cell.Offset(-1, 17)) Then
Application.Goto cell.Offset(-1, 17)
Cancel = True
MsgBox "Save is cancelled!" & _
vbNewLine & "" & vbNewLine & "Please fill in cells in column S."
End If
Next
Application.run macro:="column_S"
End Sub
You had two subroutines (column_L and column_S) that weren't being called from anywhere but, if they had been, they would have gone into an infinite loop because they called themselves.
Your code should just be placed in the BeforeSave event as follows:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim rng As Range
Set rng = Worksheets("Sheet1").Range("B7:B10000")
Cancel = True
For Each cell In rng
If Not IsEmpty(cell) Then
'Check column K of current row
If IsEmpty(cell.Offset(0, 9)) Then
Application.Goto cell.Offset(0, 9)
MsgBox "Save is cancelled!" & _
vbNewLine & vbNewLine & "Please fill in cells in column K."
Exit Sub
End If
'Check column L of current row
If IsEmpty(cell.Offset(0, 10)) Then
Application.Goto cell.Offset(0, 10)
MsgBox "Save is cancelled!" & _
vbNewLine & vbNewLine & "Please fill in cells in column L."
Exit Sub
End If
'Check column S of current row
If IsEmpty(cell.Offset(0, 17)) Then
Application.Goto cell.Offset(0, 17)
MsgBox "Save is cancelled!" & _
vbNewLine & vbNewLine & "Please fill in cells in column S."
Exit Sub
End If
End If
Next
Cancel = False
End Sub
(I removed your ScreenUpdating code, as your code doesn't actually update any cells, so I don't think you should see any flickering of the screen other than the movement caused by the GoTo, and you probably want the users to see that.)

Space check previous page and insert rows there Excel

I have block of text in (A795:O830). It is separated from other pages by Page Break and is always the last page of printed (xls, pdf) document. Sometimes there are a lot of free space on first pages and (A795:O830) could have fitted there. Now it is done by Page Break and is not changeble. In my situation 66 rows can fit on one page.
Is there any macro that can automatically check if there is enough empty space on previous page to fit (A795:O830) and insert it there?
Here is my current macro:
Sub Remove_color()
Dim myRange As Range
Dim cell As Range
Set myRange = Range("A24:O785")
For Each cell In myRange
myRange.Interior.ColorIndex = 0
Next
End Sub
Sub Hide_empty_cells()
Set rr = Range("A24:N832")
For Each cell In rr
cell.Select
If cell.HasFormula = True And cell.Value = "" And cell.EntireRow.Hidden = False Then Rows(cell.Row).EntireRow.Hidden = True
Next cell
End Sub
Sub Save_excel()
Dim iFileName$, iRow&, iCol&, iCell As Range, iArr
iFileName = ThisWorkbook.Path & "\New_folder_" & [D5] & "_" & ".xls"
iArr = Array(1, 3, 4): iCol = UBound(iArr) + 1
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlManual
ThisWorkbook.Sheets(2).Copy
With ActiveWorkbook.ActiveSheet
.Buttons.Delete '.Shapes("Button 1").Delete
.UsedRange.Value = .UsedRange.Value
.SaveAs iFileName, xlExcel8: .Parent.Close
End With
Application.Calculation = xlAutomatic
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Sub Save_pdf()
ActiveWorkbook.Sheets(2).Select
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\New_folder_\" & [D5] & "_" & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=No, _
OpenAfterPublish:=False
End Sub
Sub doitallplease()
Call Remove_color
Call Hide_empty_cells
Call Save_excel
Call Save_pdf
End Sub

Macro Copying sheets into a new workbook, editing workbook and Save As

I have recorded and used bits of code from old macros, but when I try and piece it all together it does not seem to work.
I have spent all day on google, tried breaking it up, but can't seem to get it to work.
We have a large data file with various functions in it and loads of analysis, I'd like to send out sepaerate workbooks to all these functions, but only include the relevant data.
I am trying to select 3 sheets from the main workbook, copy to a new book then edit by deleting the irrelevant rows using a filter and saving the workbook as the Function name and some other text.
I am using a list for the macro to go through to create each file with the name from the list.
Sub Create_SubFunction_Files()
    Dim iToDoRow As Integer, rSubFunction as String
    Application.ScreenUpdating = False
   For iToDoRow = 5 To 14
        If UCase(Cells(iToDoRow, 2)) = "YES" Then
            Range("rSubFunction") = Cells(iToDoRow, 1)
Sheets(Array("Data", "Risk Summary", "Checklist")).Select
Sheets("Data").Activate
Sheets(Array("Data", "Risk Summary", "Checklist")).Copy
'Filter and Delete irrelevant rows
Sheets("Data").Activate
ActiveSheet.Range("A13:OW" & UsedRange.Rows.Count).AutoFilter Field:=2, Criteria1:="<>" & Range("rSubFunction"), Operator:=xlFilterValues
Rows("14:" & UsedRange.Rows.Count).Select
Selection.Delete Shift:=xlUp
ActiveSheet.Range("A13:OW" & UsedRange.Rows.Count).AutoFilter Field:=2
  
         'Saveas target
     ActiveWorkbook.Save
     Application.DisplayAlerts = False
     ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path & "\" & Range("rSubFunction") & " " & Cells(1, 2) & " Milestone & Finance Planner " & Cells(2, 2) & ".xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End If
    Next iToDoRow
  Application.ScreenUpdating = True
   
    MsgBox "Done :)", vbExclamation
End Sub
The Declaration line, For, If and Save workbook are all highlighted in red for an error.
With my For/If statements it's not picking up the Next/End If further down, it's probably in the wrong place.
I really can't see what is wrong with the Save workbook as, even if I delete all and just leave a basic name it still has an error and highlights Filename.
Can you Step Into the following and tell me which line you get the error on?
Sub Create_SubFunction_Files()
Dim iToDoRow As Integer, rSubFunction As String
Application.ScreenUpdating = False
For iToDoRow = 5 To 14
If UCase(Cells(iToDoRow, 2)) = "YES" Then
rSubFunction = Cells(iToDoRow, 1).Value
Sheets(Array("Data", "Risk Summary", "Checklist")).Copy
'Filter and Delete irrelevant rows
Sheets("Data").Activate
ActiveSheet.Range("A13:OW" & UsedRange.Rows.Count).AutoFilter Field:=2, Criteria1:="<>" & rSubFunction, Operator:=xlFilterValues
Rows("14:" & UsedRange.Rows.Count).Select
Selection.Delete Shift:=xlUp
ActiveSheet.Range("A13:OW" & UsedRange.Rows.Count).AutoFilter Field:=2
'Saveas target
ActiveWorkbook.Save
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path & "\" & rSubFunction & " " & Cells(1, 2) & " Milestone & Finance Planner " & Cells(2, 2) & ".xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End If
Next iToDoRow
Application.ScreenUpdating = True
MsgBox "Done :)"
End Sub

Copying certain cells from a row, when criterea are met, and pasting into a new sheet

I'm trying to copy cells A:D from a row, when column E = "Accepted", and paste the data, as values, into a different sheet.
Every time I try though, it only copies the last row and I can't understand why. I'd be really grateful for any help.
My code looks like this:
Public Sub AcceptLastChangeRequest()
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
On Error GoTo errorHandler:
Dim varAnswer As String
varAnswer = MsgBox("Are you sure you wish to accept the most recent Change Request?", vbYesNo, "Accept Change Request")
If varAnswer = vbNo Then
MsgBox ("No changes saved")
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Exit Sub
End If
Dim SourceRange As Range, DestRange As Range
Dim DestSheet As Worksheet, SourceSheet As Worksheet
Dim LastRowDestSheet As Long, i As Long, LastRowSourceSheet As Long
Set DestSheet = ThisWorkbook.Worksheets("Accepted Change Requests")
Set SourceSheet = ThisWorkbook.Worksheets("All Change Requests")
LastRowDestSheet = DestSheet.Cells(DestSheet.Rows.Count, "A").End(xlUp).Row
LastRowSourceSheet = SourceSheet.Cells(SourceSheet.Rows.Count, "E").End(xlUp).Row
For i = 2 To LastRowSourceSheet
If Sheets("All Change Requests").Range("E" & i).Value = "Accepted" Then
Set SourceRange = SourceSheet.Range("A" & i, "D" & i)
Set DestRange = DestSheet.Range("A" & LastRowDestSheet + 1)
SourceRange.Copy
DestRange.PasteSpecial _
Paste:=xlPasteValues, _
operation:=xlPasteSpecialOperationNone, _
skipblanks:=False, _
Transpose:=False
Application.CutCopyMode = False
End If
Next i
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Exit Sub
errorHandler:
MsgBox ("There was an error adding this Change Request")
Resume Next
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
You are not updating the last row of the destination sheet.
Put
LastRowDestSheet = LastRowDestSheet + 1
in the end of the if-clause (after 'Set DestRange = DestSheet.Range...')
Try replacing your loop with this:
For i = 2 To LastRowSourceSheet
If SourceSheet.Range("E" & i).Value = "Accepted" Then _
DestSheet.Range("A" & LastRowDestSheet + 1 & ":D" & LastRowDestSheet + 1).Value = _
SourceSheet.Range("A" & i & ":D" & i).Value
LastRowDestSheet = LastRowDestSheet + 1
Next i
EDIT (Further OP request)
For i = 2 To LastRowSourceSheet
If SourceSheet.Range("E" & i).Value = "Accepted" Then
If Evaluate("ISERROR(MATCH(A" & i & ",'Accepted Change Requests'!A:A,0))") Then
DestSheet.Range("A" & LastRowDestSheet + 1 & ":D" & LastRowDestSheet + 1).Value = _
SourceSheet.Range("A" & i & ":D" & i).Value
LastRowDestSheet = LastRowDestSheet + 1
End If
End If
Next i

VBA Inputbox Filter enhancements

the code below works fine. However, when a user doesn't include anything in the InputBox or clicks on the 'Close' button or inputs a value which doesn't exist I want it to display a msgbox stating the reason and delete sheets 'PreTotal'.
Is there a better way to handle user input? Need some help here on how to go about it. Thank you.
Sub Filterme()
Dim wSheetStart As Worksheet
Dim rFilterHeads As Range
Dim strCriteria As String
Set wSheetStart = ActiveSheet
Set rFilterHeads = Range("M1", Range("M1").End(xlToLeft))
With wSheetStart
.AutoFilterMode = False
rFilterHeads.AutoFilter
strCriteria = InputBox("Enter Date - MMDDYY")
If strCriteria = vbNullString Then Exit Sub
rFilterHeads.AutoFilter Field:=13, Criteria1:="=*" & strCriteria & "*"
End With
Worksheets("PreTotal").UsedRange.Copy
Sheets.Add.Name = "Total"
Worksheets("Total").Range("A1").PasteSpecial
End Sub
Is this what you are trying?
Change
If strCriteria = vbNullString Then Exit Sub
to
If strCriteria = vbNullString Then
MsgBox "You choose not to continue"
Application.DisplayAlerts = False
Worksheets("PreTotal").Delete
Application.DisplayAlerts = True
Exit Sub
End If
FOLLOWUP
Thanks #Rout - This worked. One more thing what if the input criteria does not exist in the sheet? How should I tackle that? – user823911 11 mins ago
Is this what you are trying? Also if you are filtering the range based on Col M (1st Col in the range) then change the line
rFilterHeads.AutoFilter Field:=13, Criteria1:="=*" & strCriteria & "*"
to
rFilterHeads.AutoFilter Field:=1, Criteria1:="=*" & strCriteria & "*"
CODE
Sub Filterme()
Dim wSheetStart As Worksheet
Dim rFilterHeads As Range, aCell As Range
Dim strCriteria As String
Set wSheetStart = ActiveSheet
Set rFilterHeads = Range("M1", Range("M1").End(xlToLeft))
With wSheetStart
.AutoFilterMode = False
strCriteria = InputBox("Enter Date - MMDDYY")
If strCriteria = vbNullString Then
MsgBox "You choose not to continue"
Application.DisplayAlerts = False
Worksheets("PreTotal").Delete
Application.DisplayAlerts = True
Exit Sub
End If
Set aCell = .Columns(13).Find(What:=strCriteria, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
MsgBox "Search Criteria Not Found"
Exit Sub
End If
rFilterHeads.AutoFilter
rFilterHeads.AutoFilter Field:=13, Criteria1:="=*" & strCriteria & "*"
Sheets.Add.Name = "Total"
Worksheets("PreTotal").UsedRange.Copy
Worksheets("Total").Range("A1").PasteSpecial
End With
End Sub