getting error "Object Variable or With block variable not set" - vba

I have created an Add-In for Excel which determines the name of ActiveSheet and ActiveWorkbook. The code I used is below. When I run the Add-In it is showing the above mentioned error after the message box "variables set". But when I run it in macros it is working fine. I don't understand what is happening with the Add-In. Could anyone help me with this?
Sub sheetvalues()
Dim bk As Workbook, sht1 As Worksheet, sht2 As Worksheet, sht3 As Worksheet
Dim book As String, sht As String, i As Integer, j As Integer
Dim att(1 To 4) As String, att_col(1 To 4) As Integer
MsgBox ("variables set")
book = ActiveWorkbook.Name
sht = ActiveSheet.Name
MsgBox ("names set")
Set bk = Workbooks.Add
With bk
.Title = "MissingValues"
.SaveAs Filename:="MissingValues.xls"
End With
Set sht1 = bk.Sheets.Add
sht1.Name = "EndOne"
Set sht2 = bk.Sheets.Add
sht2.Name = "EndTwo"
Set sht3 = bk.Sheets.Add
sht3.Name = "EndThree"
MsgBox (book & " " & sht)
MsgBox ("completed")
End Sub

A common issue that causes this issue is forgetting to use 'Set' with assigning a value to a variable.

Check if the workbook in Excel is asking you if you want to open a write-protected version or not. I think while this question is present the workbook is not considered Active, nor is any other

Like #TimWilliams said, you will get this error if your add-in is the only workbook loaded. In that case there is no active workbook and your code is failing on the line
book = ActiveWorkbook.Name
You can check for the existence of a workbook by adding the following lines:
Set bk = Application.ActiveWorkbook
If bk Is Nothing Then
MsgBox ("No workbook open. Creating a new one.")
Set bk = Workbooks.Add(xlWBATWorksheet)
Set sht1 = bk.ActiveSheet
End If
So you end up with:
Sub sheetvalues()
Dim bk As Workbook, sht1 As Worksheet, sht2 As Worksheet, sht3 As Worksheet
Dim book As String, sht As String, i As Integer, j As Integer
Dim att(1 To 4) As String, att_col(1 To 4) As Integer
MsgBox ("variables set")
Set bk = Application.ActiveWorkbook
If bk Is Nothing Then
MsgBox ("No workbook open. Creating a new one.")
Set bk = Workbooks.Add(xlWBATWorksheet)
Set sht1 = bk.ActiveSheet
End If
book = ActiveWorkbook.Name
sht = ActiveSheet.Name
MsgBox ("names set")
Set bk = Workbooks.Add
With bk
.Title = "MissingValues"
.SaveAs Filename:="MissingValues.xls"
End With
Set sht1 = bk.Sheets.Add
sht1.Name = "EndOne"
Set sht2 = bk.Sheets.Add
sht2.Name = "EndTwo"
Set sht3 = bk.Sheets.Add
sht3.Name = "EndThree"
MsgBox (book & " " & sht)
MsgBox ("completed")
End Sub

Related

How to switch between workbooks

I have problem with switching between workbooks. Could you take a look at code and say what is wrong with attitude to problem which i am trying? Or propose some other way to do this.
Sub copy_spreadsheets()
Dim wb As Workbook, wb_main As Workbook, path As String, sheet_name As String, x As Integer, i As Integer, source_sheet As Worksheet, ws As Worksheet
path = "C:\Users\me\Desktop\folder\"
Set wb_main = ThisWorkbook
For x = 2 To 10
i = 2
sheet_name = ("sheet" & i & ".xlsx")
Set wb = Workbooks.Open(path & sheet_name)
Set sourceSheet = Worksheets("sheet1")
sourceSheet.Activate
sourceSheet.Cells.Select
Selection.Copy
Workbooks("C:\Users\me\Desktop\folder\sheet1.xls").Worksheets("Sheet1").Activate
Set ws = Sheets.Add
i = i + 1
Next x
End Sub
There is a Workbook.Activate method as well as Worksheet. Try activating the workbook before activating sheets within that workbook.

How to use two workbooks and their worksheets altogether

I am using two workbooks at a time. The first workbook is the current workbook and the second will be opened while programming execution. I have made the global objects of the workbooks and worksheets. I'm having issues with using the worksheets simultaneously. The error is ERROR: object variable or with block variable, not set. I have mentioned the error in the comment in the second subroutine.
Dim WB As Workbook
Dim WB2 As Workbook
Dim WKS As Worksheet
Dim WKS2 As Worksheet
Sub Button1_Click()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Set WB = ThisWorkbook
WB.Activate
fd.AllowMultiSelect = False
fd.Title = "Provide a title here."
fd.InitialFileName = ThisWorkbook.Path
If fd.Show() = True Then
strFile = fd.SelectedItems(1)
Set WB2 = Workbooks.Open(strFile)
Set WSK2 = WB2.Sheets("Schweitzer Analysis")
CalculateGrades
Else
MsgBox ("No file selected")
End If
End Sub
Sub CalculateGrades()
' first clear the contents where grades results can appear
clearGradesContents
Dim index As Integer ' for current sheet
Dim index2 As Integer ' for student sheet
Dim countCorrect As Integer ' to count no of correct answers
index = 2
index = 8
countCorrect = 0
' this first error here
' ERROR: object variable or with block variable not set
Set WKS = WB.ActiveSheet
Do While index <= 21
' the SECOND error shows here
If WKS.Cells(index, 2) = WKS2.Cells(index2, 3) Then
Count = Count + 1
Else
WKS.Cells(index, 5) = WKS2.Cells(index2, 3)
End If
If WKS.Cells(index, 3) = WKS2.Cells(index2, 4) Then
Count = Count + 1
Else
WKS.Cells(index, 6) = WKS2.Cells(index2, 4)
End If
index2 = index2 + 1
index = index + 1
Loop
End Sub
Sub clearGradesContents()
Range("E2:F21").Select
Selection.ClearContents
Range("I2:I3").Select
Selection.ClearContents
End Sub
EDIT: sorry for the previous answer, I hadn't seen your global declarations on top and I was sure it was because you hadn't declare it.
I think the issue is the following:
[...]
Set WB = ThisWorkbook
WB.Activate '<-- WB is the active workbook now
[...]
Set WB2 = Workbooks.Open(strFile) '<-- WB2 is the active workbook now!
Set WSK2 = WB2.Sheets("Schweitzer Analysis")
CalculateGrades '<-- going to next macro
[...]
Set WKS = WB.ActiveSheet '<-- ERROR: WB2 is the active workbook. WB can't have an active sheet if it's not the active workbook
Then of course, being WKS not correctly set, you can't execute this:
If WKS.Cells(index, 2) = WKS2.Cells(index2, 3) Then
I have no way to test it now, but I think that should be the issue.
To solve it,
If you really need WKS to be the ActiveSheet
Dim activeSheetName As String
...
Sub Button1Click()
...
Set WB = ThisWorkbook
WB.Activate
activeSheetName = WB.ActiveSheet.Name
...
End Sub
Sub CalculateGrades()
...
Set WKS = WB.Sheets(activeSheetName)
...
If you already know the name of the sheet you need
Just write:
Set WKS = WB.Sheets("your sheet")
instead of
Set WKS = WB.ActiveSheet

How do I ensure the VBA code saves the workbook to the file path declared?

The following is my code in an attempt to delete a number of sheets in order to save a workbook with specific worksheets only:
Sub SeperateWB2()
Dim ws As Worksheet
Dim wb As Workbook
Dim sheetname As Variant
Dim ddl As Variant
ddl = "PhaseTransferDropDowns"
sheetname = InputBox("Please specify sheet name:")
Path = "C:\My Documents\Phase Transfer\Test\"
For Each ws In ThisWorkbook.Worksheets 'SetVersions
If Not ws.Name = sheetname And Not ws.Name = ddl Then
Application.DisplayAlerts = False
ws.Delete
End If
Next ws
wb.SaveAs Path & ws.Name & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook
wb.Close
Set wb = Nothing
End Sub
The loop works fine but it refuses to save the workbook on the path I have specified.
I get this message: "Runtime error 91: Object variable or With block variable not set"
Can anyone help?
Look at your error message: Object variable or With block variable not set
It looks like you aren't able to save because you never instantiate your wb variable. Therefore wb = Nothing. You can't perform SaveAs on nothing. Try adding Set wb = ThisWorkbook below your declarations like so:
'other code
Dim ws As Worksheet
Dim wb As Workbook
Dim sheetname As Variant
Dim ddl As Variant
Set wb = ThisWorkbook
ddl = "PhaseTransferDropDowns"
'other code
The wb object variable is never assigned to anything other than Nothing. But anyway you can use ThisWorkook, if you mean to save and close the workbook that contains the running code:
With ThisWorkbook
.SaveAs Path & ws.Name & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook
.Close
End With
Thanks everyone!
It seems that I needed to set the workbook properly (Set wb = ThisWorkbook).
I also needed to change ws.name into sheetname.
This is the code that worked at the end:
Sub SeperateWB2()
Dim ws As Worksheet
Dim wb As Workbook
Dim sheetname As Variant
Dim ddl As Variant
Set wb = ThisWorkbook
ddl = "PhaseTransferDropDowns"
sheetname = InputBox("Please specify sheet name:")
Path = "C:\My Documents\Phase Transfer\Test\"
For Each ws In ThisWorkbook.Worksheets 'SetVersions
If Not ws.Name = sheetname And Not ws.Name = ddl Then
Application.DisplayAlerts = False
ws.Delete
End If
Next ws
wb.SaveAs Path & sheetname & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook
'wb.Close
End Sub

VBA - Copy a template worksheet and rename with user entered text

VBA novice here - I've combed the interwebs and can't seem to get this to work, it's got me stumped.
I would like to have a button on a form that will allow a user to generate a copy of a worksheet "Template", in the same workbook - to the right of "Template". I've figured it out enough that I can generate a copy that renames itself as Template(2) OR generate a blank worksheet named with the text entered in the prompt, but I can't do both.
As is below - it currently returns an "Object Required" error. Thanks in advance for your help, it's much appreciated!
Private Sub NewSheet()
Dim NewSheet As Worksheet
Dim newName As String
Do
newName = Application.InputBox("What do you want to name the new sheet?", Type:=2)
If newName = "False" Then Exit Sub: Rem cancel pressed
Set NewSheet = ThisWorkbook.Worksheets("Template").Copy(After:=Worksheets("Template"))
On Error Resume Next
NewSheet.Name = newName
newName = Error
On Error GoTo 0
If newName <> vbNullString Then
Application.DisplayAlerts = False
NewSheet.Delete
Application.DisplayAlerts = True
MsgBox newName
End If
Loop Until newName = vbNullString
End Sub
Or you can try this:
Sub Test()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("Template")
Dim newws As Worksheet, sh As Worksheet, newname
Dim query As Long, xst As Boolean, info As String
retry:
xst = False
newname = Application.InputBox("Enter a new sheet name.", info, , , , , , 2)
If newname = "False" Then Exit Sub
For Each sh In wb.Sheets
If sh.Name = newname Then
xst = True: Exit For
End If
Next
If Len(newname) = 0 Or xst = True Then
info = "Sheet name is invalid. Please retry."
GoTo retry
End If
ws.Copy after:=ws: Set newws = ActiveSheet: newws.Name = newname
End Sub
This will continuously ask for a valid sheet name unless the user cancels it.
To avoid deleting a newly added sheet, check first if the name is valid.
Also, I don't think you can copy and assign in one go since there's no documentation that the Copy Method returns the object that was copied. So you copy first and use Activesheet to assign it to a variable.

Excel hang while copying data from one workbook to another

The Excel hang if the user click the button in the sheet. The button allowed the user to run the following VBA code. If the user runs the code from VBA editor, it's working fine. Kindly help. The code is as the following. I'm trying to copy data from current excel file to the other excel file newly created.
Sub clickBreak()
i = 12
Dim workBookName As String
Dim workBookName2 As String
Dim wb2 As Workbook
Dim wb1 As Workbook
Dim pasteStart As Range
workBookName = Application.ActiveWorkbook.FullName
workBookName2 = Insert(workBookName, "_2", InStr(workBookName, ".xls") - 1) & ".xls"
MsgBox workBookName2
Dim xlobj As Object
Set xlobj = CreateObject("Scripting.FileSystemObject")
xlobj.CopyFile workBookName, workBookName2, True
Set xlobj = Nothing
Set wb1 = Workbooks.Open(Filename:=workBookName)
Set pasteStart = [A12:A15]
wb1.Sheets("contents").Range("A12:A15").Copy
Set wb2 = Workbooks.Open(Filename:=workBookName2)
wb2.Sheets("contents").Range("A12:A:15").PasteSpecial xlPasteAll
wb2.Save
End Sub
clickBreak is not an event handler. If the name of your button is Break you must name the sub
BreaK_Click() for it to act as an event handler for the button click event:
Sub BreaK_Click()
...
End Sub
Full Code:
Sub BreaK_Click()
i = 12
Dim workBookName As String
Dim workBookName2 As String
Dim wb2 As Workbook
Dim wb1 As Workbook
Dim pasteStart As Range
workBookName = Application.ActiveWorkbook.FullName
workBookName2 = Insert(workBookName, "_2", InStr(workBookName, ".xls") - 1) & ".xls"
MsgBox workBookName2
Dim xlobj As Object
Set xlobj = CreateObject("Scripting.FileSystemObject")
xlobj.CopyFile workBookName, workBookName2, True
Set xlobj = Nothing
Set wb1 = Workbooks.Open(Filename:=workBookName)
Set pasteStart = [A12:A15]
wb1.Sheets("contents").Range("A12:A15").Copy
Set wb2 = Workbooks.Open(Filename:=workBookName2)
wb2.Sheets("contents").Range("A12:A:15").PasteSpecial xlPasteAll
wb2.Save
End Sub
I got the answer
Sub clickBreak()
Dim workBookName As String
Dim workBookName2 As String
Dim wbTarget As Workbook
Dim wbThis As Workbook
Dim strName As String
Set wbThis = ActiveWorkbook
strName = ActiveSheet.Name
workBookName = Application.ActiveWorkbook.FullName
workBookName2 = Insert(workBookName, "_2", InStr(workBookName, ".xls") - 1) & ".xls"
Dim xlobj As Object
Set xlobj = CreateObject("Scripting.FileSystemObject")
xlobj.CopyFile workBookName, workBookName2, True
Set xlobj = Nothing
Set wbTarget = Workbooks.Open(workBookName2)
wbTarget.Sheets("contents").Range("A1").Select
wbTarget.Sheets("contents").Range("A12:A15").ClearContents
wbThis.Activate
Application.CutCopyMode = False
wbThis.Sheets("contents").Range("A12:A15").Copy
wbTarget.Sheets("contents").Range("A12:A15").PasteSpecial
Application.CutCopyMode = False
wbTarget.Save
wbTarget.Close
wbThis.Activate
'clear memory
Set wbTarget = Nothing
Set wbThis = Nothing
End Sub
Thanks you for spending time on my question and giving feedback. Sorry for answering my own question, I just want to share my resolution with the other who will be having the same problem.
I got reference from this http://en.kioskea.net/faq/24666-excel-vba-copy-data-to-another-workbook