Example A Procedure with a Typo

Sub NewBook()

Dim Wbk As Workbook Dim WbkName As String

' Get first open workbook Set Wbk = Workbooks(l)

' Get the workbook name WbkName = Wbk.Name

' Code to change the contents of the workbook ' goes here . . .

' Ask user for new name for document

WkbName = InputBox("Enter name for workbook " & WbkName)

' Save the workbook Wbk.SaveAs WbkName End Sub

Observe that there is a typographical error (the b and k are transposed) in the following line:

WkbName = InputBox("Enter name for workbook " & WbkName)

Since the variable WkbName is not declared, Excel will treat it as a new variable and give it the Variant data type. Moreover, VBA will assume that we want the new filename to be assigned to the variable WkbName, and will save the changed document under its original name, which is stored in WbkName. Thus, we will lose the original workbook when it is inadvertently overwritten without warning!

0 0

Post a comment