简体   繁体   中英

VBA error 1004 - Runtime

I'm having a little 'error 1004' with my project and I can't find a way to correct it "properly".

I get an error when I use this code :

If Total_account = "OUI" Or (Total_account = "NON" And Range(Cfin).Row = "2") Then GoTo fin

I am getting the error when the first condition is met:

If Total_account = "OUI"

When I have Total_account = "NON" and Range(Cfin).Row = 2, no error.

The only way to fix I found was to do it like that, but it does not look good :

If Total_account = "OUI" Then GoTo fin
If (Total_account = "NON" And Range(Cfin).Row = "2") Then GoTo fin

I also read the Microsoft support for this error but I don't get it : https://support.microsoft.com/fr-fr/help/963259/runtime-error-1004-method-range-of-object-global-failed

Could you help me understand/ find a way to correct this? The error screenshot is attached to my post.

Thanks in advance !

Jean

在此处输入图片说明

Put this code in a standard module in a new workbook. I guarantee it cannot cause an error, no matter what value you have for Total_account .

Sub foo()
Dim Total_account as String
Dim CFin as String
CFin = "$C$2"
Total_account = "OUI"

If Total_account = "OUI" Or (Total_account = "NON" And Range(CFin).Row = "2") Then GoTo fin

fin:
End Sub

This suggest a problem elsewhere in your code. Judging from the 1004 message, if the error raises on your boolean expression, this can only be because CFin is unassigned (empty string, empty/zero numeric value).

If CFin has a zero or empty value at run-time, therefore the Range(cfin) will raise a 1004 error, since Range("").Row is not valid.

Its always good to put workSheet.Range(Cfin).Row instead of Range(Cfin).Row as Perhaps your code is behind Sheet1, so when you change the focus to Sheet2 the objects cannot be found issue will happen.

Please try below code.

Sub your_sub

Dim workSheet As Worksheet
Set workSheet = ActiveWorkbook.Sheets("Sheet1") 'guessing your looking at Sheet1

Dim Cfin As String
Cfin = "$C$2"


If Total_account = "OUI" Or (Total_account = "NON" And workSheet.(Cfin).Row = "2") Then GoTo fin

MsgBox "no" 'your code

fin:

MsgBox "yes" ' your code

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM