Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and Naming Worksheet in Excel VBA [closed]

Tags:

excel

vba

I have some very simple code that adds a new Worksheet, after the current worksheets, to an Excel document, and then changes its name to one entered in a text box on a userform. Works fine on a new workbook, however in a workbook that has a number of existing worksheets it creates the new worksheet, but does not rename it.

This only happens the first time you run this code, the next time it will run fine. The thing that makes it even stranger is that if you open the VBA editor to try and debug it, it then runs fine as well. This obviously makes finding the error pretty hard.

The code I'm using is here:

     Dim WS As Worksheet       Set WS = Sheets.Add(After:=Sheets(Worksheets.count))      WS.name = txtSheetName.value 

Pretty simple. I'm wondering if this problem is that it is trying to rename the sheet before it is properly created? Is there a better way to write this code?

Update: I've started debugging this using msgboxes, as opening the debugger makes the problem stop, and it seems that it just stops processing the code halfway through:

  Dim WS As Worksheet   MsgBox (WS Is Nothing)      Set WS = Sheets.Add(After:=Sheets(Worksheets.count))     '***** Nothing after this point gets processed *******     MsgBox (WS Is Nothing)     MsgBox WS.name      WS.name = txtSheetName.value     MsgBox WS.name 
like image 771
Sam Cogan Avatar asked Oct 01 '10 15:10

Sam Cogan


People also ask

How do you name a worksheet in Excel VBA?

Renaming sheets in excel are done from the taskbar below the worksheets are present by double-clicking on them, but in VBA we use Sheets or Worksheet property method to rename the sheet, the syntax to rename a sheet in VBA is as follows Sheets(“ Old Sheet Name”). Name = “New Sheet name”.

Can macro run on closed workbook?

You can't run a macro in a workbook that is closed. You can't run a macro that affects a workbook that is closed. You can put code in Inventory.


1 Answers

http://www.mrexcel.com/td0097.html

Dim WS as Worksheet Set WS = Sheets.Add 

You don't have to know where it's located, or what it's name is, you just refer to it as WS.
If you still want to do this the "old fashioned" way, try this:

Sheets.Add.Name = "Test" 
like image 61
Sage Avatar answered Oct 04 '22 12:10

Sage