簡體   English   中英

打開 xlsm 文件時在所有工作表中自動運行 vba 宏

[英]Running Automaticaly vba Macro in all worksheets when open xlsm file

為什么在所有工作表中這個 vba 宏不能自動工作?

Private Sub Workbook_Open()
Dim cRow As Long
Dim rRow As Range
Dim LastRow As Long
Dim ws As Worksheet

For Each ws In ThisWorkbook.Worksheets
    With ws
        LastRow = [A65000].End(xlUp).Row
        For cRow = 1 To LastRow
            If Cells(cRow, 15) = "OnGoing" Then
                Rows(cRow).Font.Bold = True
                Rows(cRow).Font.Color = RGB(156, 204, 0)
            End If
            If Cells(cRow, 15) = "Modified" Then
                Rows(cRow).Font.Bold = True
            End If
        Next cRow
        Columns("A:O").EntireColumn.AutoFit
    End With
Next ws
End Sub

我做錯了什么?

創建一個名為auto_openpublic sub以在打開xlsm工作簿時運行代碼 - 您構建的內容似乎與 MS 文檔一致,但項目模塊中的auto_open始終可以正常工作。

https://support.microsoft.com/en-us/office/automatically-run-a-macro-when-opening-a-workbook-1e55959b-e077-4c88-a696-c3017600db44

如果模塊被觸發(放入一個msgbox進行驗證),那么可能是因為您沒有使用完全限定的范圍/單元格名稱,所以您需要. cellsrows的前面

            If .Cells(cRow, 15) = "OnGoing" Then
                .Rows(cRow).Font.Bold = True
                .Rows(cRow).Font.Color = RGB(156, 204, 0)
            End If
            If .Cells(cRow, 15) = "Modified" Then
                .Rows(cRow).Font.Bold = True
            End If

@freeflow 你是說這個嗎?

Private Sub Workbook_Open()
Dim cRow As Long
Dim rRow As Range
Dim LastRow As Long
Dim ws As Worksheet

For Each ws In ThisWorkbook.Worksheets
    With ws
        LastRow = ws.Cells(ws.Cells.Rows.Count, 1).End(xlUp).Row
        For cRow = 1 To LastRow
            If ws.Cells(cRow, 15) = "OnGoing" Then
                ws.Rows(cRow).Font.Bold = True
                ws.Rows(cRow).Font.Color = RGB(156, 204, 0)
            End If
            If ws.Cells(cRow, 15) = "Modified" Then
                ws.Rows(cRow).Font.Bold = True
            End If
        Next cRow
        ws.Columns("A:O").EntireColumn.AutoFit
    End With
Next ws
End Sub

它正在處理活動工作表。

您可以在進行計算之前嘗試激活工作表,因此您的代碼應如下所示

Private Sub Workbook_Open()
Dim cRow As Long
Dim rRow As Range
Dim LastRow As Long
Dim ws As Worksheet

For Each ws In ThisWorkbook.Worksheets
    With ws
        .activate
        LastRow = [A65000].End(xlUp).Row
        For cRow = 1 To LastRow
            If Cells(cRow, 15) = "OnGoing" Then
                Rows(cRow).Font.Bold = True
                Rows(cRow).Font.Color = RGB(156, 204, 0)
            End If
            If Cells(cRow, 15) = "Modified" Then
                Rows(cRow).Font.Bold = True
            End If
        Next cRow
        Columns("A:O").EntireColumn.AutoFit
    End With
Next ws
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM