VBA error 1004 - select method of range class failed

前端 未结 4 1944
臣服心动
臣服心动 2020-12-05 18:31

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 fo

相关标签:
4条回答
  • 2020-12-05 19:00

    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
    
    0 讨论(0)
  • 2020-12-05 19:02

    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)
    
    0 讨论(0)
  • 2020-12-05 19:14

    You have to select the sheet before you can select the range.

    I've simplified the example to isolate the problem. Try this:

    Option Explicit
    
    
    Sub RangeError()
    
        Dim sourceBook As Workbook
        Dim sourceSheet As Worksheet
        Dim sourceSheetSum As Worksheet
    
        Set sourceBook = ActiveWorkbook
        Set sourceSheet = sourceBook.Sheets("Sheet1")
        Set sourceSheetSum = sourceBook.Sheets("Sheet2")
    
        sourceSheetSum.Select
    
        sourceSheetSum.Range("C3").Select           'THIS IS THE PROBLEM LINE
    
    End Sub
    

    Replace Sheet1 and Sheet2 with your sheet names.

    IMPORTANT NOTE: Using Variants is dangerous and can lead to difficult-to-kill bugs. Use them only if you have a very specific reason for doing so.

    0 讨论(0)
  • 2020-12-05 19:18

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

    0 讨论(0)
提交回复
热议问题