以下代码:
Sub testingstuff()
Dim x, y As Long
x = Find_lastest_day_events("flurry_an_output.csv", "User_Session", 4)
y = Find_lastest_day_events("flurry_an_output.csv", "User_Session", 4)
Debug.Print "x is " & x
Debug.Print "y is " & y
End Sub
在立即窗口中产生以下输出:
x is 121
y is 0
究竟怎么可能?
这是功能:
Function Find_lastest_day_events(sheet_name As String, event_name As String, event_col As Integer)
' find the range of the last full day in a column and count the number of events for the last day
' use '*' in event name to just count events in range
Dim rows1 As Long
rows1 = Get_Rows_Generic(sheet_name, 1) ' total rows in sheet
Dim col1 As Integer
col1 = Range(find_last_column(sheet_name)).column ' last column number [uses address first]
Dim last_cell As Range
Dim full_range As Range
With Worksheets(sheet_name)
Set last_cell = .Range(.Cells(rows1, col1), .Cells(rows1, col1)) ' sets last_cell to the last cell in the sheet
Set full_range = .Range(.Cells(1, col1), .Cells(rows1, col1)) ' whole last column as range
End With
Dim todays_date As Long
todays_date = Date
Dim search_date As Long
search_date = todays_date - 1
Dim first_position As Long
first_position = WorksheetFunction.Match(search_date, full_range, 0)
Dim last_position As Long
last_position = WorksheetFunction.Match(search_date, full_range, 1)
Dim event_range As Range
With Worksheets(sheet_name)
Set event_range = .Range(.Cells(first_position, event_col), .Cells(last_position, event_col)) ' set the range to be searched
End With
Dim event_count As Integer
event_count = WorksheetFunction.CountIf(event_range, event_name) ' count the numbe rof events
Find_lastest_day_events = event_count
End Function
**根据评论添加**
Function Get_Rows_Generic(work_sheet_get As String, column_num As Integer)
Dim ws As Worksheet: Set ws = Worksheets(work_sheet_get)
Dim rows_count As Long: rows_count = ws.Cells(rows.Count, column_num).End(xlUp).Row
Get_Rows_Generic = rows_count
End Function
Function find_last_column(ws_name As String)
Dim ws As Worksheet
Dim rng1 As Range
Set ws = Worksheets(ws_name)
Set rng1 = ws.rows(1).Find("*", ws.[a1], xlFormulas, , xlByColumns, xlPrevious)
find_last_column = rng1.Address ' returns the address of the first cell in the last column used as a string
End Function