Заранее извиняюсь за тупость моего вопроса, но VBA занимаюсь 2-ю неделю, без литературы + времени на тщательное изучение нет, поэтому все же осмелюсь спросить: у меня есть макрос, в котором используется код: Range(«B:B,C:C,G:G,H:H,I:I»).Select До тех пор, пока работал в пределах одной процедуры — все было нормально. Прикрутил форму, для того чтобы было удобнее брать данные для переменных — начала выскакивать ошибка. Как побороть данную штуку? можно краткий ликбез, как правильно использовать переменные и методы при применении не одной процедуры, а нескольких? Спасибо. |
|
{quote}{login=knacker}{date=16.02.2009 07:24}{thema=Ошибка «method range of object _global failed»}{post} + времени на тщательное изучение нет, поэтому Как раз все эти методы описываются именно в той литературе, на изучение которой у Вас нет времени. А если у Вас нет времени на её изучение, то у людей на форуме тоже как минимум «нет времени» на то, чтобы эту литературу перепечатывать. |
|
{quote}{login=knacker}{date=16.02.2009 07:24}{thema=Ошибка «method range of object _global failed»}{post}Как побороть данную штуку? можно краткий ликбез, как правильно использовать переменные и методы при применении не одной процедуры, а нескольких?{/post}{/quote}Используя обращение к Range без указания листа (и книги) Вы получите эту ошибку, если, например, в данный момент будет активным лист диаграммы. Если вдруг у Вас Excel 2000, то рекомендуется писать так: With ThisWorkbook.Sheets(«Лист1») |
|
Ksana Пользователь Сообщений: 20 |
Добрый день! Возникла следующая проблема — у части пользователей при использовании файла с макросом выскакивает ошибка subscript out of range. У большей части все работает нормально. Проблема: надо не переписать файл (он написан старшим коллегой и исправлению не подлежит, хотя написан жутко криво), а устранить ошибку в настройках компьютера (или самого Excel?) у пользователей, у которых код глючит. Код с ошибкой — в приложенном файле. Ругается на строку Application (хотя массивом там и не пахнет и все файлы, на которых ссылается код, написаны корректно и доступны) Подскажите, что это может быть и куда копать? <EM><STRONG>Файл удален</STRONG> — велик размер — [<STRONG>МОДЕРАТОРЫ</STRONG>]</EM> |
Ksana Пользователь Сообщений: 20 |
{quote}{login=The_Prist}{date=03.03.2011 02:22}{thema=}{post}Какие общие признаки на компах с ошибкой? Может версия Excel? |
Ksana Пользователь Сообщений: 20 |
{quote}{login=The_Prist}{date=03.03.2011 02:22}{thema=}{post}Какие общие признаки на компах с ошибкой? Может версия Excel? На всех компах — Excel 2003, windows xp, настройки стандартные — разделитель точка. Глючная строка в коде выделена комментариями, это — Application.Workbooks(«KO»).Worksheets(«total data»).Activate |
Ksana Пользователь Сообщений: 20 |
Ой, извините, недооценила размер Но пожалуйста, почитайте внимательнее вопрос. Кроме того, причем здесь лист total в этой рабочей книге и лист total data (существующий, все названия правильные) в другой книге, которую макрос открывает? |
Ksana Пользователь Сообщений: 20 |
#8 03.03.2011 15:10:26 Спасибо огромное! точно, в дебагере сразу перестал ругаться |
Mr. Mickle
Thank you for the new tip. A new horizon….
the final SUB would be below. ( It worked nicely )
(it is case sensitive)
many many thanks
Sub RemoveWordTotal()
Application.ScreenUpdating = False
Dim i As Long
For i = Cells(Rows.Count, "B").End(xlUp).Row To 2 Step -1
Cells(i, "B") = Application.Substitute(Cells(i, "B"),"Total","")
Next i
Application.ScreenUpdating = True
End SubThe above can also be used to replace a text instead of just blank.
instead of "" - replace it with "New Text" !!
VERY VERSATILE CODE, Mr. Mickle..FOR OTHERS WHO MIGHT FIND THIS USEFUL:
maybe called as function (BELOW) > Call ReplaceSomeText("Total", "B", "")
"Total" (mWRD) = the word within the cell to be replaced
"B" (mcol) = the column referenced
"" (newTXT) = blank or any text to replace mWRD
Sub ReplaceSomeText(mWRD As String, mcol As String, newTXT As String)
Application.ScreenUpdating = False
Dim i As Long
For i = Cells(Rows.Count, mcol).End(xlUp).Row To 2 Step -1
Cells(i, mcol) = Application.Substitute(Cells(i, mcol),mWRD, newTXT)
Next i
Application.ScreenUpdating = True
End Sub
I’m trying to get Excel to figure out which columns of a worksheet are blank. Eventually the idea is to get it to delete the completely blank columns.
Here’s the code I have so far:
Sub Macro2()
'
' Macro2 Macro
'
Dim totalCols As Integer
Dim totalRows As Integer
totalCols = ActiveSheet.UsedRange.Columns.Count
totalRows = ActiveSheet.UsedRange.Rows.Count
Dim i As Integer
Dim j As Integer
Dim numNull As Integer
For i = 1 To totalCols
For j = 2 To totalRows
Dim location As String
location = "R" & i & ":" & "C" & j
If Range(location).Select = "" Then
numNull = numNull + 1
End If
Next j
If numNull = totalRows - 1 Then
MsgBox ("Column " & i & "is null")
End If
Next i
End Sub
At the end it checks to see if numNull
(number of null entries in the row) = totalRows minus the header. I had it working up until the statement If Range(location).Select = ""
. Now the compiler says:
Method ‘Range’ of object ‘_Global’ failed
Does anyone know what this means or how I can fix it?
asked Oct 12, 2011 at 23:24
2
Your code is using .Select
when you should be using .Value
This might be faster though:
Sub Tester()
Dim col As Range, ur As Range
Dim numRows As Long, numCols As Long, i As Long, awf
Set awf = Application.WorksheetFunction
Set ur = ActiveSheet.UsedRange
numRows = ur.Rows.Count
numCols = ur.Columns.Count
'edit: account for header row...
Set ur = ur.Offset(1,0).Resize(numRows-1, numCols)
numRows = numRows - 1
For i = numCols To 1 Step -1
Set col = ur.Columns(i)
If awf.CountBlank(col) = numRows Then
MsgBox "Column #" & col.Column & " is empty"
'col.EntireColumn.Delete
End If
Next i
End Sub
answered Oct 13, 2011 at 0:06
Tim WilliamsTim Williams
150k8 gold badges96 silver badges124 bronze badges
1
At this point ‘Range’ doesn’t refer to an instantiated object. The Range class can’t be used statically this way — you have to instantiate a Range object, usually by calling an appropriate object’s factory method. There are probably other ways to do it, but I generally call ActiveSheet.Range.
As noted by Tim Williams above, you should probably be using .Value rather than .Select; I’m not at all sure what .Select returns, the MSDN reference just says data type variant.
I’m not at a Windows machine to test, but try:
If ActiveSheet.Range(location).Value = "" Then
MSDN Range Object Reference
answered Oct 13, 2011 at 2:19
dmogledmogle
3212 silver badges4 bronze badges
1
1 2 3 4 5 |
Range("F5:F6,G5:G6,K5:K6,N5:N6,O5:O6,S5:S6,V5:V6,W5:W6,AA5:AA6,AD5:AD6,AE5:AE6,AI145:AI146,AI284:AI285,AI423:AI424,AL5:AL6,AM5:AM6,AQ145:AQ146,AQ284:AQ285,AQ423:AQ424,AT5:AT6,AU5:AU6,AY145:AY146,AY284:AY285,AY423:AY424,BB5:BB6,BC5:BC6,BG145:BG146,BG284:BG285,BG423:BG424,BJ5:BJ6,BK5:BK6,BO145:BO146,BO284:BO285,BO423:BO424,BR5:BR6,BS5:BS6,BW145:BW146,BW284:BW285,BW423:BW424,BZ5:BZ6,CA5:CA6,CE145:CE146,CE284:CE285,CE423:CE424,CH5:CH6,CI5:CI6,CM145:CM146,CM284:CM285,CM423:CM424,CP5:CP6,CQ5:CQ6,CU145:CU146,CU284:CU285,CU423:CU424").Select Selection.Copy Range("F5:F6,G5:G6,K5:K6,N5:N6,O5:O6,S5:S6,V5:V6,W5:W6,AA5:AA6,AD5:AD6,AE5:AE6,AI145:AI146,AI284:AI285,AI423:AI424,AL5:AL6,AM5:AM6,AQ145:AQ146,AQ284:AQ285,AQ423:AQ424,AT5:AT6,AU5:AU6,AY145:AY146,AY284:AY285,AY423:AY424,BB5:BB6,BC5:BC6,BG145:BG146,BG284:BG285,BG423:BG424,BJ5:BJ6,BK5:BK6,BO145:BO146,BO284:BO285,BO423:BO424,BR5:BR6,BS5:BS6,BW145:BW146,BW284:BW285,BW423:BW424,BZ5:BZ6,CA5:CA6,CE145:CE146,CE284:CE285,CE423:CE424,CH5:CH6,CI5:CI6,CM145:CM146,CM284:CM285,CM423:CM424,CP5:CP6,CQ5:CQ6,CU145:CU146,CU284:CU285,CU423:CU424").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False Application.CutCopyMode = False |
VBA 1004 Error is a runtime error in VBA. It is also known as application-defined or object-defined error. Why is that? Because we have a limited number of columns in Excel. When our code gives the command to go out of range, we get a 1004 Error. There are other situations when we get this error when we refer to a range that does not exist in the sheet.
VBA Error 1004 in Excel
VBA 1004 Error is a run time error in VBA and occurs while running the code. Errors are part and parcel of the coding, especially when writing for the first time. Therefore, you may come across many errors in VBA. However, this is common for everybody, and there is no big deal about it.
However, knowing the error of why it is coming makes you avoid those mistakes in the coming future.
In this article, we will discuss one of the important errors in Excel, “VBA 1004 Error”.
Table of contents
- VBA Error 1004 in Excel
- Top 6 Excel VBA 1004 Runtime Errors
- #1 – VBA Run Time Error 1004: That Name is already taken. Try a different One:
- #2 – VBA Run Time Error 1004: Method “Range” of object’ _ Global’ failed:
- # 3 – VBA Run Time Error 1004: Select Method of Range class failed:
- #4 – VBA Runtime Error 1004 method open of object workbooks failed:
- #5 – VBA Runtime Error 1004 method Sorry We couldn’t Find:
- #6 – VBA Runtime Error 1004 Activate method range class failed:
- Recommended Articles
- Top 6 Excel VBA 1004 Runtime Errors
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA 1004 Error (wallstreetmojo.com)
Top 6 Excel VBA 1004 Runtime Errors
You can download this VBA 1004 Error Template here – VBA 1004 Error Template
#1 – VBA Run Time Error 1004: That Name is already taken. Try a different One:
This error occurs while renaming the sheet.
If the worksheet’s name already exists. If you try to assign the same name to another sheet, VBA throws a “Run-time error ‘1004.’ ”
Look at the below code.
Code:
Sub Error1004_Example() Worksheets("Sheet2").Name = "Sheet1" End Sub
We are trying to rename sheet 2 as sheet 1. But, we already have a sheet named “Sheet1”.
If we run this code using the F5 key or manually, we will get “Run-time error ‘1004’ “: “That name is already taken. Try a different one.”
So, try renaming the sheet accordingly.
#2 – VBA Run Time Error 1004: Method “Range” of object’ _ Global’ failed:
It usually occurs when we try to access the named range in excelName range in Excel is a name given to a range for the future reference. To name a range, first select the range of data and then insert a table to the range, then put a name to the range from the name box on the left-hand side of the window.read more with a spelling mistake or that does not exist you are referring to.
For this, we have named the range of cells “Headings,” as shown in the below image.
Now, by using the RANGE object, we can access this range.
Code:
Sub Error1004_Example() Range("Headings").Select End Sub
If you run this code by pressing the F5 key, then this code will select the named range.
But, if we mention the named range wrongly, we will get “Run-time error ‘1004.’ “Method “Range” of object’ _ Global” failed.
Code:
Sub Error1004_Example() Range("Headngs").Select End Sub
Run this code manually or use the F5 key and see the result.
# 3 – VBA Run Time Error 1004: Select Method of Range class failed:
It usually occurs when we try to select the cells other than the active sheet without making the sheet select or active.
Look at the below code.
Code:
Sub Error1004_Example() Worksheets("Sheet1").Range("A1:A5").Select End Sub
The above code says to select the cells A1 to A5 in the worksheet “Sheet1”. However, to experiment, my present active sheet is “Sheet2”, not “Sheet1”.
We will run this code using the F5 key or manually to see what happens.
We got “Run-time error ‘1004.’ “Select method of Range class failed” as without activating the sheet; we try to select the cells of that sheet. So first, we need to activate the sheet before we select the cells. Below is the correct code.
#4 – VBA Runtime Error 1004 method open of object workbooks failed:
It usually occurs when you try to open the workbook, which has the same name as the other workbook we have already opened.
Look at the below code.
Code:
Sub Error1004_Example() Dim wb As Workbook Set wb = Workbooks.Open("FileName.xls", ReadOnly:=True, CorruptLoad:=xlExtractData) End Sub
It will throw the below error.
#5 – VBA Runtime Error 1004 method Sorry We couldn’t Find:
This error occurs when you try to open the file which does not exist in the mentioned path. For example, it could move, be renamed, or deleted from the mentioned path. One reason for this is the wrong type of path or file name with the excel extensionExcel extensions represent the file format. It helps the user to save different types of excel files in various formats. For instance, .xlsx is used for simple data, and XLSM is used to store the VBA code.read more.
Now, take a look at the below code.
Code:
Sub Error1004_Example() Workbooks.Open Filename:="E:Excel FilesInfographicsABC.xlsx" End Sub
This code says to open the file “ABC.xlsx” in the mentioned folder path.
We know there is no file in the mentioned folder path. So, we will get the: Run-time error ‘1004’ method when no file exists in the mentioned folder. Sorry, and We couldn’t find it.
#6 – VBA Runtime Error 1004 Activate method range class failed:
This error occurs mainly due to activating the range of cells without activating the worksheet.
Look at the below code.
Code:
Sub Error1004_Example() Worksheets("Sheet1").Range("A1:A5").Activate End Sub
This error is similar to the one we have seen in Run-time error’ 1004′: Select method of Range class failed.
If we run manually or use the F5 key, we will get the below error.
Because without activating the sheet, we cannot activate the cells in it. So first, activate the sheet and then activate the cells of that sheet.
Recommended Articles
This article has been a guide to VBA 1004 Error. Here, we discuss the top 6 types of 1004 run-time errors in VBA and how to fix them, along with examples and downloadable templates. Below are some useful articles related to VBA: –
- VBA LEN Function
- VBA Type Mismatch Error
- VBA Sub Procedures
- VBA Match Function