简体   繁体   中英

VBA code to update a column on Workbook_Open

I've been muddling my way through a bit of VBA to improve a request tracker we use at my place of work having done some VB.NET a decade or so ago in Highschool. Trial and error with some googling to find answers when I'm stuck has served me well but I cannot for the life of me figure this one out...

I want to run some code when the workbook is opened to update cells in a specific column. I got this to work on the Worksheet_Change event but that would be running it too often and as the number of records grows I fear it would slow things down.

My problem is that I do not know the syntax to reference the column when I am not in the worksheet code. My (feeble) attempt was as follows:

            Private Sub Workbook_Open()
                If ThisWorkbook.Sheets("2016").Columns(10).Value = "x" Then
                    ThisWorkbook.Sheets("2016").Columns(11).Value = Application.WorksheetFunction.NetworkDays(ThisWorkbook.Sheets("2016").Columns(7).Value, Date) - 1
                End If
            End Sub

The idea is that if Column J contains an x Column K should display the number of working days between the value in Column G (date request was logged) and today's date so that it shows how long the request has been outstanding

there is no need of macro, it can be done by using the below formula

 =IF(J1="x",NETWORKDAYS(G1,TEXT(NOW(),"mm/dd/yyyy"))-1) 

If you want to be done via macro only the hope the code will help you :)

 Private Sub Workbook_Open() l = Sheets("2016").Columns(10).End(xlDown).Row For c = 1 To l If Cells(c, 10).Value <> "" Then a = Sheets("2016").Cells(c, 7).Value b = Application.WorksheetFunction.Text(Now(), "mm/dd/yyy") If ThisWorkbook.Sheets("2016").Cells(c, 10).Value = "x" Then ThisWorkbook.Sheets("2016").Cells(c, 11).Value = WorksheetFunction.NetworkDays(a, b) - 1 End If End If Next c End Sub 

If you want to address any cell in a specific column please use cells(row_no, col_no)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM