2014-01-11 70 views
3

我已經嘗試了一切,包括在論壇上閱讀關於錯誤1004應用程序定義或對象定義的錯誤,但我找不到任何東西,正在幫助我修復錯誤。它在立即窗口中寫入正確的公式。這裏是代碼。我已經把代碼中的錯誤放在了哪裏。Error 1004 vba excel當進入到單元格中的查找公式

變量的定義主要有以下幾種,我已經在錯誤1004

Dim templateName As String  ' = "Company 1" and yes this worksheet exists in my file 
Dim servicesRow As Integer  ' = 22 
Dim j as Integer     ' = 1 
Public firstProjectSOF as Range ' firstProjectSOF.Row = 5 
Dim columnTemp As Variant  ' columnTemp(0) = "A" 
Public lastProjectSOF as Range ' lastProjectSOF.Row = 65 
Dim Rng as Range     ' Rng.Column = 17 



For j = 1 To numEmployees 

    With Sheets("SOF").Range("E5", Range("E5").End(xlToRight))  'Finds the cell in SOF of that employee's last name 
     Set Rng = .Find(What:=employees_lastName(j), _ 
        LookIn:=xlValues, _ 
        LookAt:=xlPart, _ 
        SearchOrder:=xlByColumns, _ 
        SearchDirection:=xlNext, _ 
        MatchCase:=False) 
    End With 
    'This is where the error 1004 occurs, on trying to write the VLOOKUP formula into the cell 

    Sheets(templateName).Range(Cells(servicesRow + 1 + j, 5)).FormulaLocal = "=VLOOKUP($G$10,'Staff Output Final'!B" & firstProjectSOF.Row & ":" _ 
    & columnTemp(0) & lastProjectSOF.Row & "," & (Rng.Column - 1) & ",FALSE)" 
Next 

對於信息的時間包含在監視窗口中的值,如果是相關的,我的電腦是從Mac加拿大(英文),但我最近在法國的一臺PC電腦上編輯了這個文件(使用法文版的操作系統)。爲了防止出現問題,我只是嘗試在我的Mac上創建一個新的excel文件,並將舊文件中的選項卡複製並粘貼到新文件中,但仍然收到Error 1004 ...

謝謝你的幫助!非常感激!

+1

你在哪裏初始化'lastProjectSOF'? –

+0

對不起,「初始化」是什麼意思?你的意思是「我賦值的地方」?我使用一個輸入框,Set lastProjectSOF = Application.InputBox(Prompt:=「在Staff Output Final中,選擇列B中具有項目編號的最後一個單元格」,標題:=「STAFF OUTPUT FINAL,Last Cell in Range」, Type:= 8) – sox373

+0

我剛剛添加了'lastProjectSOF'是一個Public變量的信息。 – sox373

回答

1

其實,我只是想偶然的東西,它的工作....我刪除範圍,和剛剛離開的細胞部分,所以代碼變成了:

Sheets(templateName).Cells(servicesRow + 1 + j, 5).FormulaLocal = "=VLOOKUP($G$10,'Staff Output Final'!B" & firstProjectSOF.Row & ":" _ 
& columnTemp(0) & lastProjectSOF.Row & "," & (Rng.Column - 1) & ",FALSE)" 

我不明白爲什麼這個工程,但它確實....

有誰知道爲什麼?由於在相同的代碼中更高,我使用下面的代碼將VLOOKUP公式分配給另一個單元,並且它與「Range」一起工作沒有問題。

Sheets(templateName).Range("A18:H18").FormulaLocal = "=VLOOKUP($G$10,'PEIINV2 - paste here'!B" & firstProjectPEIINV.Row & ":AH" & lastProjectPEIINV.Row & _ 
",2,FALSE)" 
+1

如果您只有一個參數,則範圍對象所需的Cell1必須是A1樣式引用;你的Cells參數返回一個範圍對象。閱讀HELP的Worksheet.Range屬性,但它很混亂。如果你使用類似range(cells(1,1).address)的東西,它會工作,但不是範圍(單元格(1,1)) –

+0

感謝Ron,是的,你說得對,它適用於範圍(單元格(1, 1)。地址)。我很欣賞這個解釋,因爲我試着在線閱讀範圍和單元格的屬性,但沒有發現任何會讓我失望的東西。這可能就是我錯過了它。無論如何,再次感謝!乾杯 – sox373

0
Sheets(templateName).Range(Cells(servicesRow + 1 + j, 5)) 

你的出發碼錯過細胞前片(TEMPLATENAME)(...),所以如果activesheet不TEMPLATENAME,它可能會引發錯誤。

你也可能需要更改

With Sheets("SOF").Range("E5", Range("E5").End(xlToRight)) 

With Sheets("SOF").Range("E5", sheets("SOF").Range("E5").End(xlToRight))