2013-10-22 72 views
1

我已經創建了一個表格來重新格式化我收到的報告,並且我在自動化它的一部分時遇到了問題。一切工作,直到我定義和設置最後一個變量的代碼長度,我想設置一個單元格的長度(第一列,第二行)在一個定義的範圍內。我收到運行時錯誤424,「Object Required」。我感謝任何幫助!VBA對象所需的錯誤

下面是代碼:

Private Sub CommandButton1_Click() 


Application.ScreenUpdating = False 

Dim rg As Range 
Dim rgg As Range 
Dim Addr1 As String 
Dim Addr2 As String 

'Get the address, or reference, from the RefEdit control. 
Addr1 = RefEdit1.Value 
Addr2 = RefEdit2.Value 

'Set the SelRange Range object to the range specified in the 
'RefEdit control. 
Set rg = Range(Addr1) 
Set rgg = Range(Addr2) 

ActiveWorkbook.Names.Add Name:="codes", RefersTo:=rgg 

'Infill 
'Copies the value from the row above into blank cells. 
Dim cel As Range, col As Range 
Set rg = Range(Addr1).Columns(1).Resize(, 2) 
On Error Resume Next 
For Each col In rg.Columns 
    Set rgg = Nothing 
    Set rgg = col.SpecialCells(xlCellTypeBlanks) 
    If Not rgg Is Nothing Then 
     rgg.FormulaR1C1 = "=R[-1]C"  'Blank cells set equal to value from row above 
     rgg.Formula = rgg.Value 'Optional: Replace the formulas with the values returned by the formulas 
    End If 
Next 
Set rgg = rg.Offset(1, 0).Resize(rg.Rows.Count - 1, rg.Columns.Count) 
For Each cel In rgg.Cells 
    If cel = "" Then cel.Value = cel.Offset(-1, 0).Value 
Next 
On Error GoTo 0 

'ColCDeleter 
Dim i As Long, n As Long 
Set rg = Intersect(ActiveSheet.UsedRange, Range(Addr1).Columns(3)) 
n = rg.Rows.Count 
For i = n To 1 Step -1 
If rg.Cells(i, 1) = "" Then rg.Cells(i, 1).EntireRow.Delete 
Next 

'insert corresponding values 
Dim codelength As Integer 
codelength = Len(codes.Cells(2, 1).Value) 
rg.Columns(2).EntireColumn.Insert 
rg.Columns(2).EntireColumn.Insert 
rg.Columns(2).EntireColumn.Insert 
rg.Columns(2).EntireColumn.Insert 
If codelength = 6 Then 
rg.Columns(2).FormulaR1C1 = "=VLOOKUP((MID(RC1,9,9)),codes,2,FALSE)" 
rg.Columns(3).FormulaR1C1 = "=VLOOKUP((MID(RC1,9,9)),codes,3,FALSE)" 
Else 
rg.Columns(2).FormulaR1C1 = "=VLOOKUP((MID(RC1,8,9)),codes,2,FALSE)" 
rg.Columns(3).FormulaR1C1 = "=VLOOKUP((MID(RC1,8,9)),codes,3,FALSE)" 
End If 
rg.Cells(1, 2).Value = "Plan" 
rg.Cells(1, 3).Value = "Status" 


'Unload the userform. 
Unload Me 



End Sub 
+5

將本幫助'LEN(範圍( 「代碼」)。將細胞(2,1)。價值的rng Range對象)' – 2013-10-22 15:47:47

+0

正是我需要的......謝謝! – kcraig23

回答

1

當您第一次使用以下語法

Dim rng as Range 
Set rng = Range("A1:A10") 

ActiveWorkbook.Names.Add Name:="codes", RefersTo:=rng 

那麼這將成爲只是一個名字命名的範圍 - 它不是一個獨立的對象。所以你得到的錯誤告訴你到底發生了什麼 - >需要對象。

要引用命名範圍,請將其用雙引號括起來,並將其作爲Range對象的參數。因此,Range("codes")會創建一個指向rng範圍的Range對象。

的替代,省略名稱將是使用簡單地替換Range("codes").rng.