因此,我正在學習 VBA,并試圖讓這段代碼從作業表 1 的第 3 行開始運行 Q 列,并將其結果與作業表 2 的第 4 行開始的 F 列進行比較。如果為真,則突出顯示有問題的單元格黃色(我寧愿突出顯示整行,如果你能幫忙,那就太棒了!)。
Sub CompareValues()
Set ws1 = Application.Workbooks("Book1.xlsx").Sheets("Sheet1")
Set ws2 = Application.Workbooks("Book2.xls").Sheets("Sheet2") ' the xls is correct
startRow = 3
ws1Value1Col = "Q"
ws1EndRow = ws1.UsedRange.Rows(ws1.UsedRange.Rows.Count).Row
ws2Value1Col = "F"
ws2EndRow = ws2.UsedRange.Rows(ws2.UsedRange.Rows.Count).Row
For i = startRow To ws1EndRow
If Not ws1.Cells(i, ws1Value1Col).Value = ws2.Cells(i 1, ws2Value1Col).Value Then
wsl.Cells(i, ws1Value1Col).Value = vbYellow
End If
Next
End Sub
我收到錯誤 424:需要物件。
在谷歌搜索過去一個小時后,我離解決這個問題還差得很遠。我嘗試了多種建議無濟于事。作業簿和作業表都在運行時打開。
uj5u.com熱心網友回復:
我已經為此構建了一個解決方案,該解決方案遵循 BigBen 提出的要Option Explicit在您正在構建的模塊頂部使用的初始點。
這樣做的原因是因為 VBA 將強制您為您打算使用的每個變數定義型別,下面的解決方案將向您展示這一點。否則,隱式理解的型別是Variant,它有其應用程式,但從記憶體使用的角度來看也非常低效。
Option Explicit
Sub CompareValues()
Dim ws1 As Worksheet, ws2 As Worksheet, startRow As Integer
Dim ws1Col As Integer, ws2Col As Integer, ws1EndRow As Integer, ws2EndRow As Integer
Dim i As Integer
Dim cell As Range
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
startRow = 3
ws1Col = 1
ws1EndRow = ws1.UsedRange.Rows(ws1.UsedRange.Rows.Count).Row
ws2Col = 2
ws2EndRow = ws2.UsedRange.Rows(ws2.UsedRange.Rows.Count).Row
For i = startRow To ws1EndRow
If Not ws1.Cells(i, ws1Col).Value = ws2.Cells(i 1, ws2Col).Value Then
Set cell = ws1.Cells(i, ws1Col)
cell.Interior.Color = vbYellow
End If
Next
End Sub
讓我們看一下:
- 我將您的兩個作業表變數、列、結束行和起始行定義為整數。
- 然后我使用一個單元格變數作為范圍物件,其目的是解決您遇到的錯誤。
- 定義每列使用范圍的代碼很好,另一種方法是使用“
End(xlUp).Row”,作為設定資料動態范圍的一種方式。 - 您擁有的 For Loop 和 If-Then 條件是標準問題并且是適當的。
- 這里的新時刻是我將使用Set關鍵字將所需的單元格分配給代碼中的同名變數。
- 之后,您可以使用Interior.Color方法將所需的值突出顯示為黃色。
請注意,我使用整數來指定此版本代碼中的列。你的方法不會出錯,但如果你打算使用Cells,那么我認為你應該堅持使用統一的整數型別來參考行和列;這也是編碼的一般良好做法。
希望這可以幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/535462.html
標籤:擅长VBA办公室365
