Worksheet function Sum-if causing error type mismatch - excel

I am looping through the worksheets to sumif the amounts that are "C" and "D".
Each tabs have the amounts in column M and whether they are credit or debit in column N, indicated by the letter C or D.
First I am putting the letters C and D on blank cells and trying to sumif these two amounts next to them.
I am getting a type mismatch error at the sumif line and the whole line is highlighted.
At first I thought maybe it was ws = Worksheets(I) causing the problem so I swapped them out with Worksheets(I), but it still did not work.
Sub Sumiftabs()
Dim Filepath As String
Dim UIGFile As Workbook
Dim Column As String
Dim Month As String
Dim Year As Integer
Dim I As Long
Dim TY As Integer
Dim TYLetter As String
Dim T As Long
Dim TreatyYear As Long
Dim WS_Count As Integer
Dim ws As Worksheet
Application.ScreenUpdating = False
TreatyYear = Sheets("Control").Range("B7").Value
'On Error Resume Next
For T = TreatyYear To 16 Step -1
TYLetter = WorksheetFunction.VLookup(T, Workbooks("Separate tabs.xlsm").Sheets("Control").Range("H:I"), 2, False)
TY = Sheets("Control").Range("B7").Value
Month = Sheets("Control").Range("B5").Value
Year = Sheets("Control").Range("B4").Value
Filepath = Sheets("Control").Range("B2").Value
Set UIGFile = Workbooks.Open("K:\Ayoon\UIG\" & Year & "\" & Month & "\UIG_NSA_MonYear_TY" & T & ".xls")
WS_Count = UIGFile.Worksheets.Count
For I = WS_Count To 1 Step -1
Set ws = Worksheets(I)
'Direct Premium
UIGFile.Worksheets(I).Range("S4").Value = "C"
UIGFile.Worksheets(I).Range("S5").Value = "D"
UIGFile.Worksheets(I).Range("T4").Value = _
Application.WorksheetFunction.SumIf(ws.Range("N:N"), ws.Range("S:S"), ws.Range("M:M"))
UIGFile.Worksheets(I).Range("T5").Value = _
Application.WorksheetFunction.SumIf(ws.Range("N:N"), ws.Range("S:S"), ws.Range("M:M"))
Next I
UIGFile.Close savechanges:=True
Next T
Application.ScreenUpdating = True
End Sub

Your SUMIF looks incorrect.
Eg try this instead:
UIGFile.Worksheets(I).Range("T4").Value = _
Application.WorksheetFunction.SumIf(ws.Range("N:N"), "C", ws.Range("M:M"))

Related

Why is my VBA SUMIFS function returning zeros?

First, allow me to thank you for any help you are able to lend me. I appreciate it! (:
My issue is this: I have two workbooks, one with raw data, and one in which the raw data is consolidated into relevant statistics. I am trying to SUMIFS the data in X:X in my raw data workbook (6620) by two criteria in the results book and then update the value in the corresponding cell in the results book.
The problem is that the macro returns all zeros. I have double checked the data types, names, ranges, etc, but no luck. Leaving me to think there is something wonky in my code.
I include two photos at the end of this post of example raw data and results tables so you can see what I am working from.
Sub ImportFTEs()
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim ws As Integer
Workbooks.Open Filename:=ActiveWorkbook.Path & "\6620\FY19*.xlsb"
For ws = 1 To Worksheets.Count
Sheets(ws).Name = "Sheet1"
Next ws
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim l As Integer
Dim totalFTE As Long
Dim lastRow As Integer
lastRow = Cells(Rows.Count, "D").End(xlUp).Row
Dim wb_a As Worksheet
Set wb_a = Workbooks.Open(ActiveWorkbook.Path & "\FY19*.xlsb").Sheets("Sheet1")
Dim wb_b As Worksheet
Set wb_b = ThisWorkbook.Sheets("B")
Dim sumRange As Range
Set sumRange = wb_a.Range("X:X")
Dim cRange1 As Range
Set cRange1 = wb_a.Range("D:D")
Dim criteria1 As Range
Dim cRange2 As Range
Set cRange2 = wb_a.Range("S:S")
Dim criteria2 As Range
For k = 8 To 18
For l = 7 To 18
For i = 7 To 18
Set criteria1 = wb_b.Cells(7, i)
For j = 8 To 18
Set criteria2 = wb_b.Cells(j, 6)
wb_b.Cells(k, l).value = Application.WorksheetFunction.SumIfs(sumRange, cRange1, criteria1, cRange2, criteria2)
Next j
Next i
Next l
Next k
ActiveWorkbook.Close savechanges:=True
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
You don't need so many nested loops. Your original code is looping through every possible criteria for each k and l. Assuming wb_b.Cells(k, l) is supposed to be a reference to the cell intersected by your month column and employee name row, you could use your i and j values.
For i = 7 To 18
Set Criteria1 = wb_b.Cells(7, i)
For j = 8 To 18
Set Criteria2 = wb_b.Cells(j, 6)
wb_b.Cells(j, i).Value = Application.WorksheetFunction.SumIfs(sumRange, cRange1, Criteria1, cRange2, Criteria2)
Next j
Next i

Why am I receiving Error 1004 when trying to specify the loop variable in a cell reference?

I am stuck, primarily because I am still brand spanking new at VBA. As such, I really appreciate any help you can lend me. I have looked through many other Error 1004 posts on here, but they were either for different issues, or it is quite possible that I am just too ignorant to know what to do with the advice in them.
My issue is this: I have two workbooks, one with raw data, and one in which the raw data is consolidated into relevant statistics. I am trying to sumif the data in X:X in my raw workbook (6620) by two criteria in the statistics book and then update the value in the corresponding cell in the statistics book.
I am running into a Run-time Error 1004: Application-defined or object-defined error at the indicated points. I am lost as to how to move past this.
Any help is greatly appreciated!
This is as far as I have gotten:
Option Explicit
Sub ImportFTEs()
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim ws As Integer
Workbooks.Open Filename:=ActiveWorkbook.Path & "\6620\FY19*.xlsb"
For ws = 1 To Worksheets.Count
Sheets(ws).Name = "Sheet1"
Next ws
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim l As Integer
Dim totalFTE As Long
Dim lastRow As Integer
lastRow = Cells(Rows.Count, "D").End(xlUp).Row
Dim wb As Worksheet
Set wb = Workbooks.Open(ActiveWorkbook.Path & "\FY19*.xlsb").Sheets("Sheet1")
Dim wc As Worksheet
Set wc = ThisWorkbook.Sheets("B")
Dim sum1R As Range
Set sum1R = wb.Range("X:X")
Dim arg2R As Range
Set arg2R = wb.Range("D:D")
Dim arg2C As Range
Set arg2C = wc.Cells(7, i)
>>> Error 1004
Dim arg3R As Range
Set arg3R = wb.Range("S:S")
Dim arg3C As Range
Set arg3C = wc.Cells(j, 6)
>>> Error 1004
For k = 8 To 18
For l = 7 To 18
For i = 7 To 18
For j = 8 To 18
wc.Cells(k, l).value = Application.WorksheetFunction.SumIfs(sum1R, arg2R, arg2C, arg3R, arg3C)
Next j
Next i
Next l
Next k
ActiveWorkbook.Close savechanges:=True
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Should be something like this - you need the Set lines containing i and j inside their respective loops - that way the values actually increment (and aren't 0 when they're initialized):
Option Explicit
Sub ImportFTEs()
Application.ScreenUpdating = False
Application.EnableEvents = False
Workbooks.Open Filename:=ActiveWorkbook.Path & "\6620\FY19*.xlsb"
Dim i As Long, j As Long, k As Long, l As Long
Dim totalFTE As Long
Dim wb As Worksheet
Set wb = Workbooks.Open(ActiveWorkbook.Path & "\FY19*.xlsb").Sheets("Sheet1")
Dim wc As Worksheet
Set wc = ThisWorkbook.Sheets("B")
Dim sum1R As Range
Set sum1R = wb.Range("X:X")
Dim arg2R As Range
Set arg2R = wb.Range("D:D")
Dim arg3R As Range
Set arg3R = wb.Range("S:S")
Dim arg2C As Range
Dim arg3C As Range
For k = 8 To 18
For l = 7 To 18
For i = 7 To 18
Set arg2C = wc.Cells(7, i)
For j = 8 To 18
Set arg3C = wc.Cells(j, 6)
wc.Cells(k, l).Value = Application.WorksheetFunction.SumIfs(sum1R, arg2R, arg2C, arg3R, arg3C)
Next j
Next i
Next l
Next k
ActiveWorkbook.Close True
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub

How can I fix this macro to work between two workbooks?

My code is working when I just use a single workbook and communicate between sheets but gives me subscript out of range errors and object not defined errors when I attempt to reference a cell range in a sheet contained in a different work book. Right now, the error is occurring at "Set pidat = Worksheets("pidat")
Dim pival As Double
'Dim eom As Worksheet 'declaring pidat worksheet as variable
'Set eom = Worksheets("EOM") 'declaring eom worksheet as variable
'Set Inv_Level = Worksheets("Inv_Levels")
Dim pidat As Worksheet 'declaring eom worksheet as variable
Set pidat = Worksheets("pidat")
Dim steve As Workbook
Set steve = Application.Workbooks("EOM Report VBA")
Dim EOMAs As Workbook
Set EOMAs = Application.Workbooks("EOMA")
Dim Inv_Level As Worksheet
'These changes allow for a dynamic range to be referenced outside of the active sheet/workbook
Dim location As String
Dim rownum As Long
Dim loopy As Long
Dim fRng As Range
Dim J As Long
Dim rn As Date
Dim last As Date
Dim rnm As Integer
Dim lastm As Integer
Dim tyear As Long
Dim K As Long
With pidat
J = .Range("J2").Value
rn = Now
last = .Range("B1").Value
rnm = month(rn)
lastm = month(last)
tyear = year(rn)
If lastm < rnm Then
.Range("B1") = (rnm & "/" & "01" & "/" & tyear & " 07:30")
J = J + 100
.Range("J2") = J
End If
End With
K = J + 100
'names of workbook/sheet referenced
With steve
rownum = .Range("E" & Rows.Count).End(xlUp).Row 'counts the number of rows in the location tag column
For loopy = 3 To rownum 'Data values start after row 3, loops through each row in the column
If .Range("E" & loopy) <> "" Then
location = .Range("E" & loopy)
'newloc = location
With Inv_Level
Set fRng = .Cells.Range("A" & J, "ZZ" & K).Find(What:=location, LookIn:=xlFormulas, LookAt:=xlPart) 'eom can be any sheet you need to perform the .Find again
End With
If Not fRng Is Nothing Then
fRng.Offset(0, -1) = pidat.Range("D" & loopy)
Else: End If
'if the search item is not found, do nothing, go to next loop
End If
Next loopy
End With
End Sub
You need to qualify the specific workbook you want to work with.
The line Set pidat = Worksheets("pidat") will fail if the active workbook at the time this line is executed has no worksheet named pidat.
Here is an example of how to qualify a workbook
Dim theWorkbook as Workbook
Set theWorkbook = Application.Workbooks("myWorkbook")
Dim pidat as Worksheet
Set pidat = theWorkbook.Worksheets("pidat")
You could go one step further and verify that a sheet named pidat (or whatever) exists in the qualified workbook, but I'll leave you to discover how to do that :)

How to delete rows in Excel based on certain values

I have a workbook with 10 sheets. Each sheet has about 30,000 rows with URL. I have a hand full of URLs (about 10 different URLs) that I need to keep the data. Is there a way to delete all the rows from all the worksheet if the first column (Column A - URL) does not contain one of the URL.
for example, I would like to keep we.abc.us, ss.boli.us and 3m.mark.us and delete rest of the rows from all the worksheet in the workbook.
Sub delete0rows()
Dim Worksheet As Excel.Worksheet
Dim lastRow As Long
Dim i As Integer
For Each Worksheet In Application.ThisWorkbook.Worksheets
lastRow = Worksheet.Cells(Rows.Count, 1).End(xlUp).Row
i = 1
Do While i <= lastRow
If Worksheet.Range("A" & i).Value = 0 Then
Worksheet.Rows(i).Delete i = i - 1
lastRow = lastRow - 1
End
i = i + 1
Loop
Next Worksheet
End Sub
I suggest you introduce reverse For loop using Step -1:
Sub delete0rows()
Dim Worksheet As Excel.Worksheet
Dim lastRow As Long
Dim i As Integer
For Each Worksheet In Application.ThisWorkbook.Worksheets
lastRow = Worksheet.Cells(Rows.Count, 1).End(xlUp).Row
For i = lastRow To 1 Step -1
If Worksheet.Range("A" & i).Value = 0 Then
Worksheet.Rows(i).EntireRow.Delete
End If
Next i
Next Worksheet
End Sub
I found this sub a while back. I cannot remember who the original author was or I would credit them. I did tweak it slightly to pass variables into it
The nice thing about this is you can pass multiple deletion criteria by passing a space separated string
Essentially you can give it a row to start at (in case you have headers) tell it the column to look in, the sheet that column is on and your criteria/criterion. So for example if I want it to start at row 5 checking each row below that on a sheet named 'cleanup' checking column 'D' for the words 'cat' 'dog' and 'fish' I would write
Call DelRow(5,"D","cleanup","cat dog fish")
Public Sub DelRow(DataStartRow As Long, SearchColumn As String, SheetName As String, myTextString As String)
' This macro will delete an entire row based on the presence of a predefined word or set of words.
'If that word or set of words is 'found in a cell, in a specified column, the entire row will be 'deleted
'Note the seperator is a space. To change this modify the split parameter
'EXAMPLE CALL: Call DelRow(1, "AH", "Cut Data", "DEL")
Dim X As Long
Dim Z As Long
Dim LastRow As Long
Dim FoundRowToDelete As Boolean
Dim OriginalCalculationMode As Integer
Dim RowsToDelete As Range
Dim SearchItems() As String
SearchItems = Split(myTextString)
On Error GoTo ResetCalcs
OriginalCalculationMode = Application.Calculation
Application.Calculation = xlCalculationManual
With Worksheets(SheetName)
LastRow = .Cells(.Rows.Count, SearchColumn).End(xlUp).Row
Application.StatusBar = "**** Working on the '" & SheetName & "' Sheet: Number of Rows to be scanned(" & LastRow & "). Deletion keyword " & myTextString & " ***" 'Extra line added
For X = LastRow To DataStartRow Step -1
FoundRowToDelete = False
For Z = 0 To UBound(SearchItems)
If InStr(.Cells(X, SearchColumn).Value, SearchItems(Z)) Then
FoundRowToDelete = True
Exit For
End If
Next
If FoundRowToDelete Then
If RowsToDelete Is Nothing Then
Set RowsToDelete = .Cells(X, SearchColumn)
Else
Set RowsToDelete = Union(RowsToDelete, .Cells(X, SearchColumn))
End If
If RowsToDelete.Areas.Count > 100 Then
RowsToDelete.EntireRow.Delete
Set RowsToDelete = Nothing
End If
End If
Next
End With
If Not RowsToDelete Is Nothing Then
RowsToDelete.EntireRow.Delete
End If
ResetCalcs:
Application.Calculation = OriginalCalculationMode
End Sub

Inserting Cell Values Into Specified Cell

I am a complete beginner with Excel VBA. I am trying to produce a schedule tracker which has on the "Courses" worksheet all the teaching information of courses running.
Column E uses a formula to identify the cell which cross references the staff member and the course date.
Column K contains the concat (text & Numerical data) statement which I need to have inserted into the correct place on the "Calendar" worksheet (same workbook).
The Code I have so far is shown below:
Private Sub BtnUpdate_Click()
Dim w As Variant
Dim c As Variant
Dim i As Integer
Dim n As Integer
'Application.ScreenUpdating = False
i = 1
w = Sheets("Courses").Range("E" & i).Value
c = Sheets("Courses").Range("K" & i).Value
Do
Sheets("Calendar").Range(w).Select
ActiveCell.Value = c.Value
Loop While n <> Range("E2").End(xlDown).Row
'Application.ScreenUpdating = True
End Sub
Any guidance would be greatly appreciated.
Not too clear .. but you may try this ..
Private Sub BtnUpdate_Click()
Dim w As Variant
Dim c As Variant
Dim i, n As Integer
Dim r as Range
Set r = Range("E65536").End(xlup)
'Application.ScreenUpdating = False
For i = 1 to r.Row
w = Sheets("Courses").Range("E" & i).Value
c = Sheets("Courses").Range("K" & i).Value
Sheets("Calendar").Range(w).Select
ActiveCell.Value = c.Value
'Application.ScreenUpdating = True
Next
End Sub

Resources