[vb.net] VBA error 1004 - select method of range class failed

First time poster, so if there is any formatting, or guidelines I failed to adhere to, please let me know so that I can fix it.

So I am basically asking the user for the file directory of the excel file, then I setup some variables (originally set at public as project variables, since these were being used and changed in other places). I have also added the lines to set these variables to nothing (just in case, I do not think that it should matter). I then set these variables to the excel file, workbook, and sheets that I want to access.

Dim filepath as String
filePath = CStr(fileDialog)              'ask file dir, set to string
Dim sourceXL As Variant                  'these three were orig project variables
Dim sourceBook As Variant
Dim sourceSheet As Variant
Dim sourceSheetSum As Variant

Set sourceXL = Nothing                    'set to nothing in case...?
Set sourceBook = Nothing
Set sourceSheet = Nothing
Set sourceSheetSum = Nothing

Set sourceXL = Excel.Application          'set to the paths needed
Set sourceBook = sourceXL.Workbooks.Open(filePath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")

Dim measName As Variant                    'create variable to access later
Dim partName As Variant

sourceSheetSum.Range("C3").Select           'THIS IS THE PROBLEM LINE

measName = sourceSheetSum.Range(Selection, Selection.End(xlDown)).Value
sourceSheetSum.Range("D3").Select
partName = sourceSheetSum.Range(Selection, Selection.End(xlDown)).Value

So I created two different sheet variables 'sourceSheets' and 'sourceSheetsSum', the code works if i use 'sourceSheets', but error 1004 occurs if i use 'sourceSheetsSum'. I have also tried the code with the variable 'sourceSheet' removed completely, in case that was overriding 'sourceSheetSum' for some reason.

I am fairly confident that the excel workbook and sheets exist and are being called correctly, since I ran a quick bit of code to loop through all the sheets in the workbook and output the names, shown below.

For j = 1 To sourceBook.Sheets.Count
Debug.Print (Sheets(j).name)
Next j

With the debug output of

Measurements
Analysis Summary
Analysis Settings

So, does anyone have any ideas what this error could mean, or how I can possibly go about finding more about what the error actually is?

EDIT: So I decided to add a bit to the listing of the sheet names, not sure if it will help at all.

For j = 1 To sourceBook.Sheets.Count
    listSheet(j) = Sheets(j).name
Next j    
Debug.Print (listSheet(2))    
Set sourceSheetSum = sourceBook.Sheets(listSheet(2))

The debug prints Analysis Summary, so I know that the sheet exists in the workbook, and there should not be any issues with a 'typo' in the names.
The code still has the same error at the same line though.

deusxmach1na: I think you wanted me to change

Dim sourceXL As Variant                  
Dim sourceBook As Variant
Dim sourceSheet As Variant
Dim sourceSheetSum As Variant

Set sourceSheet = sourceBook.Sheets("Measurements")

To

Dim sourceXL As Excel.Application
Dim sourceBook As Excel.Workbook
Dim sourceSheet As Worksheet
Dim sourceSheetSum As Worksheet

Set sourceSheet = sourceBook.Worksheets("Measurements")

But this does not change the error, I remember I had it similar to that, and then changed it since I read that variant is like a catch all, not actually that solid on what variant is.

This question is related to vb.net excel excel-2010 powerpoint vba

The answer is


You can't select a range without having first selected the sheet it is in. Try to select the sheet first and see if you still get the problem:

sourceSheetSum.Select
sourceSheetSum.Range("C3").Select

Removing the range select before the copy worked for me. Thanks for the posts.


assylias and Head of Catering have already given your the reason why the error is occurring.

Now regarding what you are doing, from what I understand, you don't need to use Select at all

I guess you are doing this from VBA PowerPoint? If yes, then your code be rewritten as

Dim sourceXL As Object, sourceBook As Object
Dim sourceSheet As Object, sourceSheetSum As Object
Dim lRow As Long
Dim measName As Variant, partName As Variant
Dim filepath As String

filepath = CStr(FileDialog)

'~~> Establish an EXCEL application object
On Error Resume Next
Set sourceXL = GetObject(, "Excel.Application")

'~~> If not found then create new instance
If Err.Number <> 0 Then
    Set sourceXL = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0

Set sourceBook = sourceXL.Workbooks.Open(filepath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")

lRow = sourceSheetSum.Range("C" & sourceSheetSum.Rows.Count).End(xlUp).Row
measName = sourceSheetSum.Range("C3:C" & lRow)

lRow = sourceSheetSum.Range("D" & sourceSheetSum.Rows.Count).End(xlUp).Row
partName = sourceSheetSum.Range("D3:D" & lRow)

Examples related to vb.net

How to get parameter value for date/time column from empty MaskedTextBox HTTP 415 unsupported media type error when calling Web API 2 endpoint variable is not declared it may be inaccessible due to its protection level Differences Between vbLf, vbCrLf & vbCr Constants Simple working Example of json.net in VB.net How to open up a form from another form in VB.NET? Delete a row in DataGridView Control in VB.NET How to get cell value from DataGridView in VB.Net? Set default format of datetimepicker as dd-MM-yyyy How to configure SMTP settings in web.config

Examples related to excel

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Converting unix time into date-time via excel How to increment a letter N times per iteration and store in an array? 'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data) How to import an Excel file into SQL Server? Copy filtered data to another sheet using VBA Better way to find last used row Could pandas use column as index? Check if a value is in an array or not with Excel VBA How to sort dates from Oldest to Newest in Excel?

Examples related to excel-2010

Get list of Excel files in a folder using VBA filter out multiple criteria using excel vba Swap x and y axis without manually swapping values Excel 2010 VBA - Close file No Save without prompt Removing special characters VBA Excel Creating a list/array in excel using VBA to get a list of unique names in a column Excel formula to get week number in month (having Monday) Excel VBA Run-time Error '32809' - Trying to Understand it IF statement: how to leave cell blank if condition is false ("" does not work) Excel how to find values in 1 column exist in the range of values in another

Examples related to powerpoint

Make just one slide different size in Powerpoint powerpoint loop a series of animation VBA error 1004 - select method of range class failed PPT to PNG with transparent background What is a correct MIME type for .docx, .pptx, etc.? How to name an object within a PowerPoint slide? Embed a PowerPoint presentation into HTML

Examples related to vba

Copy filtered data to another sheet using VBA Better way to find last used row Check if a value is in an array or not with Excel VBA Creating an Array from a Range in VBA Excel: macro to export worksheet as CSV file without leaving my current Excel sheet VBA: Convert Text to Number What's the difference between "end" and "exit sub" in VBA? Rename Excel Sheet with VBA Macro Extract Data from PDF and Add to Worksheet Quicker way to get all unique values of a column in VBA?