如何使用设定范围变量激活工作表?
例如
Dim WorkRng1 as Range
Range.WorkRng1.Activate
如果我在两个工作簿之间使用范围变量,则此代码不起作用。
我在不同的工作簿中设置这些范围:
Dim xTitleId As String
xTitleId = "Compare Ranges"
Set WorkRng1 = Application.InputBox("Please Select TASK ID Range in **INVOICE REVIEW FILE**", xTitleId, Type:=8)
Set WorkRng2 = Application.InputBox("Please Select TASK ID Range in **BUDGET GRID**", xTitleId, Type:=8)
Set WorkRng3 = Application.InputBox("Please Select **UNIT COST** Range in Budget Grid", xTitleId, Type:=8)
Call CompareRanges
'Error Handler
Whoa:
Select Case Err.Number
Case 1004
MsgBox "Check Your Column Letters!", vbInformation, "Oops!"
Case 424
Exit Sub
End Select
然后运行在不同工作簿中发生的这些循环:
'clears color format
WorkRng2.Interior.ColorIndex = xlNone
'finds duplicate values
For Each Rng1 In WorkRng1
For Each Rng2 In WorkRng2
If Rng1.Value = Rng2.Value Then
Rng2.Interior.Color = VBA.RGB(254, 255, 255)
Exit For
End If
Next
Next
'find unique values and highlights red
For Each Rng2 In WorkRng2
For Each Rng3 In WorkRng3
If Rng2.Value > 0 And Cells(Rng2.Row, Rng3.Column) <> 0 And Rng2.Interior.Color <> VBA.RGB(254, 255, 255) Then
Rng2.Interior.Color = VBA.RGB(255, 0, 0)
Exit For
End If
Next
Next
'prompts to select blank row to copy
Set blkRow = Application.InputBox("Please select the 'BLANK' with formulas", "BLANK ROW SELECTION", Type:=8)
'****NEED HELP HERE
'finds unit id below unique value in range 1 and inserts blank row
'i is range 1
Dim i As Variant
'q is range 2
Dim q As Variant
For i = WorkRng1.Cells.Count To 1 Step -1
For q = WorkRng2.Cells.Count To 1 Step -1
If Cells(q, WorkRng2.Column).Interior.Color = VBA.RGB(255, 0, 0) And Cells(q, WorkRng2.Column).Value > 0 Then
If Cells(i, WorkRng1.Column).Value = Cells(q, WorkRng2.Column).Offset(1, 0).Value Then
blkRow.Copy
Cells(i, WorkRng1.Column).EntireRow.Insert Shift:=xlDown
Application.CutCopyMode = False
Exit For
End If
End If
Next
Next
我需要在循环组之间激活工作簿
答案 0 :(得分:2)
如果你有范围,但没有范围的工作表,那么你可以使用范围的.Parent
属性来激活它。 / p>
Dim rng1 As Range
Set rng1 = Worksheets(2).Range("A2")
rng1.Parent.Activate
但是,您可以通过在设置Range对象之前正确声明Worksheet对象并使用它们来轻松避免此问题。