Excel VB Workbook_Open() only works manually - excel

I have a workbook that open another workbook and copies a range of data over. After that it does some data collection and sends an email. The issue I have is that the Workbook_Open() function to autorun this when the workbook is open does not work correctly. If I have the original workbook open and run it from the VB editor all works fine. If however, I let it run automatically it hangs and says the "Select method of the Worksheet class has failed"
Private Sub Workbook_Open()
Call send_Mail
End Sub
Private Sub send_Mail()
Dim Mail As CDO.Message
Set Mail = New CDO.Message
Dim strFilename As String: strFilename = "S:\Office\Requisition Logs\FY22\FY 2022.xlsx"
Dim wb2 As Workbook
Set wb2 = Workbooks.Open(Filename:=strFilename)
Dim vals As Variant
'Store the value in a variable:
vals = wb2.Sheets("FY2022 Log").Range("A2:AJ500").Value
'Close wb2:
wb2.Close savechanges:=False
Dim wb1 As Workbook
Set wb1 = ThisWorkbook
'Use the variable to assign a value to the other file/sheet:
wb1.Sheets("FY2022 Log").Range("A2:AJ500").Value = vals
wb1.Sheets("FY2022 Log").Select
Dim x As Integer
x = 1
Dim lastRow As Integer
Dim lastCol As Integer
Dim startRow As Integer
Dim numRows As Integer
startRow = 2
.............................
I do have the Workbook_Open() in the Workbook tab of the ThisWorkbook

Related

User Profile in VBA

I have some code which I want to share with other users and so when they run the workbook from their Downloads folder, I want each user to be able to run it. Basically username1 will change for each user.
I tried the examples -> HERE
Here is the code I have:
Sub CopyTime()
Dim rFind As Range
Dim rDelete As Range
Dim strSearch As String
Dim iLookAt As Long
Dim bMatchCase As Boolean
Dim WS7 As Worksheet
Const csvFile = "C:\Users\username1\Downloads\Login_Logout_Report.csv"
Dim ws As Worksheet, csv As Workbook, cCount As Long, cName As String
Dim wb1 As Excel.Workbook
Set wb1 = Workbooks.Open("C:\Users\username1\Downloads\ShiftTime.xlsm")
' Other code goes here
End Sub
Here is what I have tried
Const csvFile = "C:\Users\" & Environ("UserName") & "\Downloads\Login_Logout_Report.csv"
Dim ws As Worksheet, csv As Workbook, cCount As Long, cName As String
Dim wb1 As Excel.Workbook
Set wb1 = Workbooks.Open("C:\Users\" & Environ("UserName") & "\Downloads\ShiftTime.xlsm")

cant seem to set workbook as a variable

I can't seem to get my two open workbooks to set as variables. I have created a sub that opens the second one, so both now should be open.
But when I step through the code I get:
"rn-time error'438' object doesn't support this property or method.
I have tried both .Select and Activate. Both come back with errors.
have included the sub that opens the second workbook, for reference.
Sub copytoMaster()
Dim wkbk As Workbook
Dim NewFile As Variant
NewFile = "C:\Users\msheppar\Desktop\new holiday project\Master Holiday Tracker.xlsm"
If NewFile <> False Then
Set wkbk = Workbooks.Open(NewFile)
End If
End Sub
Sub CopyAndPaste()
Dim wbpast As Workbook
Dim wbcop As Workbook
Dim xlastrowcopy As Long
Dim xlastrowpast As Long
Dim xlastcolumnn As Long
Dim i As Integer
Dim j As Integer
Dim r As Integer
Dim rname As String
Set wbcop = Workbooks("Holiday form (9).xlsm")
Set wbpast = Workbooks("Master Holiday Tracker.xlsm")
'For i = 1 To xlastrowcopy
wbcop = ActiveSheet
Sheets("sheet4").Select

Macro runs faster when run from developer pane, but extremley slow when called from userform

I am run the same piece of VBA code in Excel in two different ways.
1. From the developer tab, takes less than 2 sec.
2. Calling the macro from a userform, takes over a minute and freezes
Here is the code:
Sub Import()
Dim wbSource As Workbook
Dim wbDest As Workbook
Dim TargetSheet As Worksheet
Dim c As Range
Dim rng As Range
Dim i As Integer
Dim MyRange As Range
Dim SourceSheet As Worksheet
Dim source As String
Dim dest As String
Dim r As Range
Dim msg As String
source = Worksheets("Set-Up").Range("B11")
dest = Worksheets("Set-Up").Range("B8")
Set wbSource = Workbooks(source)
Set SourceSheet = wbSource.Worksheets("HFL01 Extract")
Set wbDest = Workbooks(dest)
Set TargetSheet = wbDest.Worksheets("INPUTS1")
With SourceSheet.Range("A1").CurrentRegion
For Each r In TargetSheet.Range("A1:N1") 'Range("A1:cc1")
Set c = .Rows(1).Find(r.Value, , , xlWhole, , 0)
If Not c Is Nothing Then
.Columns(c.Column).Copy
r.PasteSpecial xlPasteValues
End If
Next
Application.CutCopyMode = False
End With
Set fileDialog = Nothing
Set wbSource = Nothing
End Sub
Why does running the macro in different ways cause it to be slow? How do I make the macro run at the same speed when called from the userform?

how to write a code in vba so each time a function call its create a different sheet in a workbook

Public Sub text1(st As String)
Dim oXL As Object ' Excel application
Dim oBook As Object ' Excel workbook
Dim oSheet As Object ' Excel Worksheet
Dim i As Integer
'Start Excel and create a new workbook
Set oXL = CreateObject("Excel.application")
Set oBook = oXL.Workbooks.Open("E:\karan.xlsx")
Set ws = oBook.Sheets.Add
oBook.activesheet.Name = st
ws.Activate
To what I understand you, you would like to add a workbook when your function is called. In such a case you could use this:
Sub AddWorkbook()
Sheets.Add After:=Sheets(Sheets.Count)
End Sub
If you additionally want to add a name:
Private Sub AddWorkbookWithName(workbookName As String)
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Select
Sheets(Sheets.Count).Name = workbookName
End Sub
Sub AddWorkbook()
AddWorkbookWithName ("MyWorkbookName")
End Sub

Start empty Excel workbook without any worksheets

Creating a new Excel workbook as in:
Dim xl As Excel.Application
Dim wb As Excel.Workbook
Set xl = New Excel.Application
xl.Visible = False
Set wb = xl.Workbooks.Add
Is there an easy way to stop Excel automatically creating Sheet1, Sheet2, Sheet3?
I can always delete these unwanted sheets afterwards but that feels like a clunky solution.
xl.SheetsInNewWorkbook = 1
More Information on MSDN (Scroll down to Add method as it applies to the Workbooks object.)
Full Code:
Dim xl As Excel.Application
Dim wb As Excel.Workbook
Dim restoreSheetsInNewWorkbook As Long
Set xl = New Excel.Application
restoreSheetsInNewWorkbook = xl.SheetsInNewWorkbook
xl.SheetsInNewWorkbook = 1
Set wb = xl.Workbooks.Add
xl.SheetsInNewWorkbook = restoreSheetsInNewWorkbook 'or just set it to 3'
Or you can:
Excel 2003
Tools>Options>General Tab and change the "Sheets in new workbook" to 1
Excel 2007
Office Button>Excel Options>Popular Section>When creating new workbooks...>Include this many sheets>1
Can't create one without any sheets (to the best of my knowledge), but you can create a workbook with a single sheet without messing around with the user's settings.
dim wb as Workbook
Set wb = xl.Workbooks.Add(xlWBATWorksheet)
Sub DeleteSheets()
Dim DeleteSheet As Variant
Dim ws As Worksheet
DeleteSheet = Array("Sheet1", "Sheet2", "Sheet3")
Application.DisplayAlerts = False
For Each ws In Worksheets
If IsInArray(ws.Name, DeleteSheet) Then ws.Delete
Next
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
Dim i As Integer
Dim Ret As Boolean
Ret = False
For i = LBound(arr) To UBound(arr)
If VBA.UCase(stringToBeFound) = VBA.UCase(arr(i)) Then
Ret = True
Exit For
End If
Next i
IsInArray = Ret
End Function

Resources