Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Run-time error '1004':

0

I am using Excel 2016.  I ran through the tutorial named 

Input Form to Get Data and Store it in Another Tab in Excel

I want to be able to enter data and press a button to autofill a second excel spreadsheet.  I am getting a "Run-time error '1004':" and "Method 'Range of object'_Global'" failed. Is there someone who can help?

Here is my code

Sub data_input()

ws_output = "Data"

next_row = Sheets(ws_output).Range("A" & Rows.Count).End(xlUp).Offset(1).Row

Sheets(ws_output).Cells(next_row, 1).Value = Range("first_name").Value

Sheets(ws_output).Cells(next_row, 2).Value = Range("last_name").Value

Sheets(ws_output).Cells(next_row, 3).Value = Range("email").Value

Sheets(ws_output).Cells(next_row, 4).Value = Range("account").Value

End Sub

Answer
Discuss

Answers

0

Hi Dappelgate and welcome to the Forum

Your code will only work in the same workbook (as the tutorial title suggests). You may have named ranges like first_name but unless they're single cells, you'll get repeated results (first entry in range). You could use:

Range("first_name").Offset(1).Value
to get the second value (and use an incrementing counter variable like n instead of the number 1 to get higher values).

Look instead at Don's tutorial Macro to get Data from Another Workbook in Excel. If you follow that and assign Wb1, then you can copy whole ranges (from your second workbook) like this example pasting the values of 4 x 50 entries:

Sub data_input()

Dim Wb1 As Workbook

Application.ScreenUpdating = False

ws_output = "Data"

next_row = Sheets(ws_output).Range("A" & Rows.Count).End(xlUp).Offset(1).Row

Set Wb1 = Workbooks.Open("E:\Documents\test1.xlsx")

With ThisWorkbook.Sheets(ws_output)
    Wb1.Sheets(1).Range("A1:A50").Copy
    .Cells(next_row, 1).PasteSpecial Paste:=xlPasteValues
    Wb1.Sheets(1).Range("D1:D50").Copy
    .Cells(next_row, 2).PasteSpecial Paste:=xlPasteValues
    Wb1.Sheets(1).Range("G1:G50").Copy
    .Cells(next_row, 3).PasteSpecial Paste:=xlPasteValues
    Wb1.Sheets(1).Range("J1:J50").Copy
    .Cells(next_row, 4).PasteSpecial Paste:=xlPasteValues
End With

Wb1.Close SaveChanges:=False

Application.ScreenUpdating = True

End Sub
You'll need to change the bits in bold (especially the fill file path/name on the  line including Workbooks.Open).

Note that the With/ End With section specifies ThisWorkbook (e.g. so VBA doesn't look for a sheet called "Data" in the second workbook.

Hope this helps.

Discuss


Answer the Question

You must create an account to use the forum. Create an Account or Login