'Getting "object variable not set" error when trying to write to new sheet

I am trying to simultaneously read from one sheet and print to another sheet, with additional format.

I think my issue has to do with improperly referencing the two sheets, as I am fairly new to this.

The sheet I am reading is called "datasheet." I assume I would refer to it like this:

ThisWorkbook.Worksheets("datasheet")

I created my new sheet using the following line:

Set formattedSheet = ActiveWorkbook.Sheets.Add(After:=ActiveWorkbook.Worksheets(ActiveWorkbook.Worksheets.Count))

Then I set up my header row, which is being printed properly to the new sheet.

After that, I need to take more data from the original sheet and write over to the new one.

But when I reference the old sheet, I get runtime error 91, object variable or with block not set.

For Each piCell In Sheets("datasheet").Range("D" & dataRowOffset & ":D" & bottomRow)
                printToColumn = payrollItems(piCell.Value)
                printToColumnString = Split(Cells(1, printToColumn).Address, "$")(1)
                rng = ThisWorkbook.WorkSheets("datasheet").Range("E" & piCell.row & ":" & horizontalOffsetString & piCell.row)    
                formattedSheet.Range( _
                    printToColumnString & _
                    printRowOffset & ":" & _
                    printToColumnString & _
                    verticalOffset) _
                = Application.WorksheetFunction.Transpose(rng)
Next piCell

Can anyone help me? I am assume it has to do with how I am referencing the sheets.

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source