Question : Getting an error in Excel, when trying to run VBA code

Not an excel expert, I have a form in Excel, and I want to copy data from one sheet to the other so that it prints the correct information for each employee.  Here is the VB code:

   Function RangeName(sName As String) As String
    RangeName = Application.Substitute(sName, " ", "_")
End Function
Sub MergePrint()

    Dim wsForm As Worksheet, wsData As Worksheet
    Dim sRngName As String, r As Long, c As Integer
    Set wsForm = Worksheets("Form")
    Set wsData = Worksheets("Data")
    With wsData.Cells(1, 1).CurrentRegion
        For r = 2 To .Rows.Count
            If Not wsData.Cells(r, 1).EntireRow.Hidden Then
                For c = 1 To .Columns.Count
                    sRngName = wsData.Cells(1, c).Value
                    Range(RangeName(sRngName)).Value = wsData.Cells(r, c)
                Next
                wsForm.PrintOut
            End If
        Next
    End With
End Sub

I am getting a Runtime error 1004,

Method 'Range' of object '_Global' failed.

I don't know what is incorrect, can you help??

Answer : Getting an error in Excel, when trying to run VBA code

Your code is checking every cell in the worksheet that isn't in a hidden row.  Obviously there are going to be some empty cells in the worksheet, and when you use

    Range(RangeName(sRngName)).Value = wsData.Cells(r, c)

That is going to evaluate to Range("").Value is my guess, and Excel doesn't know what to do with that.

Try changing your code to only check columns that have a header.  Assuming your table on wsData is contiguous (meaning every column from A to the right has a header),

Something like



1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
Sub MergePrint()

    Dim wsForm As Worksheet, wsData As Worksheet
    Dim sRngName As String, r As Long, c As Integer
    Set wsForm = Worksheets("Form") 
    Set wsData = Worksheets("Data")
    With wsData.Cells(1, 1).CurrentRegion
        For r = 2 To .Rows.Count
            If Not wsData.Cells(r, 1).EntireRow.Hidden Then
                For c = 1 To .Range("A1").End(xlToRight).Column
                    sRngName = wsData.Cells(1, c).Value
                    Range(RangeName(sRngName)).Value = wsData.Cells(r, c)
                Next
                wsForm.PrintOut
            End If
        Next
    End With
End Sub
Random Solutions  
 
programming4us programming4us