Bruno Ferreira
Bruno Ferreira

Reputation: 21

how to refer to a worksheet in a workbook?

manage to get to here but cannot delete the columns in the worksheet, can you please help? Sorry, big mess even to post the questions

Private Sub CommandButton2_Click() ' DELETE ROWS AND COLUMNS (TRIM FILE)

Sheets("RAW DATA FILE").Range("1:7").EntireRow.Delete

Sheets("RAW DATA FILE").Columns("v" & "x" & "z" & "ab" & "ad" & "af" & "ag" & "ah" & "ai" & "aj" & "ak" & "al").EntireColumn.Delete

End Sub

Can someone help please?

Upvotes: 0

Views: 121

Answers (1)

Plutian
Plutian

Reputation: 2309

There are a few ways you can refer to another worksheet in a workbook, and even refer to another workbook.

Refer to another sheet with Sheets( or Worksheets(. This can take two arguments, either a sheet number Sheets(1), but I find this unreliable as it sometimes is hard to keep track of the proper sheet numbers when adding and removing sheets. The best way is to refer directly by the sheet name: Sheets("Sheetname"). Please note there is a slight difference in using Sheets or Worksheets.

As SJR pointed out there is a third way to refer to sheets with the sheet codename. The codename is the name of the sheet displayed in your VBA window. You can get the codename of your sheet with Debug.Print Sheet("name").Codename. And you can refer directly to this sheet like so Sheet1.Range("A:A") etc.

To make sure you refer to the right sheet within the workbook you have open, and prevent yourself from having your VBA run in another workbook you have open at the same time use either Activeworkbook.Sheets, which refers to the workbook which is currently active, or Thisworkbook.Sheets which refers to the specific workbook the VBA code is in. You can also use Workbook("Workbook name").sheets.

Some further reading for you.

Upvotes: 1

Related Questions