Run time error '9' VBA - excel

I get the error 'Subscript Out of Range' when I run the following code; debug points me to the last line:
Dim SrcBook As Workbook
Dim TrgBook As Workbook
Dim SrcSheet As Worksheet
Dim TrgSheet As Worksheet
Dim Sheet_Name As String
Workbooks.Open (CalendarFile)
Sheet_Name = MonthName(Month(SrcSheet.Cells(SrcRow, "D").Value), False)
MsgBox ("Sheet_Name Value is: " & Sheet_Name)
Set TrgSheet = Workbooks(CalendarFile).Worksheets(Sheet_Name)
I have repeatedly verified that CalendarFile is a valid file name (I use the full path filename). Sheet_Name is also the valid name of a sheet in that Workbook. I get a similar error if I try to access the worksheets via numeric indexing [ie, Workbooks(CalendarFile).Worksheets(11) vs Workbooks(CalendarFile).Worksheets(November)]. The MsgBox call verifies that I'm feeding the WorkSheets() method the proper sheet name.
Lastly, ScrRow is properly defined - I am able to use this code to manipulate target WorkSheets in the same WorkBook as the macro is called from in toy/testing applications, but for some reason it is failing when I try to manipulate target WorkSheets in other (open) WorkBooks.
Any help would be greatly appreciated! Thank You!

If CalendarFile is a valid filename, that's your issue. The index you need for Workbooks() is the Workbook.Name, not its file path. For example, if CalendarFile was C:\Foo\Bar.xlsx, you need to use Bar.xlsx.
As for the explanation above, it really doesn't matter because you should really just grab a the reference that Workbooks.Open returns and just use that:
Set TrgBook = Workbooks.Open(CalendarFile)
Sheet_Name = MonthName(Month(SrcSheet.Cells(SrcRow, "D").Value), False)
MsgBox ("Sheet_Name Value is: " & Sheet_Name)
Set TrgSheet = TrgBook.Worksheets(Sheet_Name)

Found the solution, at least to this problem:
Workbooks.Open (CalendarFile)
Requires the full-path-name of the file to open, but further references to the file require just the file name - without any of the path attached. That is,
Workbooks(file_name_without_path.xlsx).Worksheets(Sheet_Name)
This is extremely annoying and should be fixed.

Related

How to reference a workbook without opening it

I want to open a new workbook, and run some macro inside, at the end will paste the result to the new workbook.
I tried different method to reference other workbooks path because I need the data inside, however, I cant do it correctly. Below is my coding:
Sub stepTen()
Dim wbLinelist As String, wsLinelist As String
wbLlinelist = "C:\Users\abc\Excel\trial\ppp.xlsx"
wsLinelist = "Sheet1"
Dim llStyle As Long
Dim colllStyle, As String
With Workbooks(wbLlinelist).Worksheets(wsLinelist)
llStyle = Application.Match("fire", .Rows(1), 0)
colllStyle = Split(Cells(1, llStyle).Address, "$")(1)
End With
End Sub
Dim colllStyle, As String is no valid syntax remove the comma.
Here Cells(1, llStyle).Address it is not specified in which workbook and worksheet the Cells object is meant to be. It should start with a dot .Cells(…) if you want it to use the With statement or you must specify a workbook/worksheet.
If Application.Match("fire", .Rows(1), 0) does not match it returns an error. So you must check if it matched or errored using the IsError function:
If Not IsError(llStyle) Then
'split
Else
'error message
End If
And finally your main issue is that you cannot use a full path "C:\Users\abc\Excel\trial\ppp.xlsx" in Workbooks(wbLlinelist). You must open a workbook using the Workbooks.Open method before you can access it.
Dim MyOpenWb As Workbook
Set MyOpenWb = Application.Workbooks.Open(FileName:=wbLlinelist) 'you might want to open it read only and set the parameter ReadOnly:=True
With MyOpenWb.Worksheets(wsLinelist)
'your code
End With
Don't forget to close the workbook in the end:
MyOpenWb.Close SaveChanges:=False

How to define a cell value as a worksheet

I'm currently using a fixed file name in my code however I'd like to replace this fixed name with the value of a particular cell
I've looked extensively across threads to no luck - I'm quite new to coding so I've found similar issues but nothing I'm able to apply to my coding or adapt for exactly my needs
I've tried using
Set wbBook2 = Workbooks(wsSheet1_1.Range("O35").Value)
and a few other similar steps but to no avail
Dim wbBook1 As Workbook
Dim wsSheet1_1 As Worksheet
Dim wsSheet1_2 As Worksheet
Dim wbBook2 As Workbook
Dim wsSheet2_1 As Worksheet
Set wbBook1 = Workbooks("Main File.xlsm")
Set wsSheet1_1 = wbBook1.Worksheets("Example1")
Set wsSheet1_2 = wbBook1.Worksheets("Example2")
Set wbBook2 = Workbooks("Look Up File.xlsm")
Set wsSheet2_1 = wbBook2.Worksheets("Example3")
The above allows me to use 'wbBook2.Activate' to switch to the workbook where the data is located & take the necessary actions however I'd like to be able to change from using "Look Up File.xlsm" to cell O35 on wsSheet1_1.
Currently I'm just ensuring my look-up file has the same name as is noted in the code but this would obviously lead to failure if this is accidentally re-named or a user titled this LookUp File (omitting the space) for example.
Note that 'wbBook2' will already be open when this code is used & the file name can change. The user separately defines the full file path & name (including .xlsm) which is then opened in a separate macro that needs to remain separate
It's safer to loop through Workbooks and look for a match
Private Function set_wb(ByVal toName As String) As Workbook
' Function set_wb(<String>), returns Workbook Object on match.
' - if no match found, return Nothing
' - invokation example: Set wb1 = set_wb("Book1")
Dim wb As Workbook
For each wb in Application.Workbooks
If wb.Name = toName Then
Set set_wb = wb ' wb found
Exit Function
End If
Next wb
Set set_wb = Nothing ' wb not found
End Function
And would be invoked in your case the following way:
Set wbBook2 = set_wb(wsSheet1_1.Range("O35"))

How to Import a Sheet from an external Workbook AND use the Filename (WITHOUT the .datatype at the end ) as the New Worksheet name?

How to import a Sheet from an external Workbook AND use the Filename (WITHOUT the .datatype at the end) as the new Worksheet name?
The part with WITHOUT the .datatype at the end I meant because I could split the filename from the file path with UBound, but when I try to do that with the filename and the filetype at the end, it doesn't work and gives me an error. Perhaps i dont understand ubound
well enough.
I found this Sub somewhere here on the forum.
But I don't want to import any sheet except the sheet which has the same name as the file itself. So I am not even sure if you need to specify the sheet name.
So I have this Excel file with VBA macros. And the Sheet is called Blank (Since I can't have an excel file without a sheet inside it) and
I have a Userform button where I browse for the file first, and the sheet there should be imported to my Excel File and delete the Blank sheet and import the new EXTERNAL sheet.
Also, it should import ANY Sheet from the file path. Because the names will always be different.
And also, how do I import the data as csv?
I am googling but I don't see what exactly causes it to be imported as csv at other peoples solutions.
Sub ImportSheet()
Dim sImportFile As String, sFile As String
Dim sThisBk As Workbook, wbBk As Workbook
Dim vfilename As Variant
Dim wsSht As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set sThisBk = ActiveWorkbook
sImportFile = Application.GetOpenFilename( _
FileFilter:="Comma Separated Value, *.csv", Title:="Open Workbook")
If sImportFile = "False" Then
MsgBox "No File Selected!"
Exit Sub
Else
vfilename = Split(sImportFile, "\")
sFile = vfilename(UBound(vfilename))
Application.Workbooks.Open Filename:=sImportFile
Set wbBk = Workbooks(sFile)
With wbBk
If SheetExists("GaebTesten.g42_2") Then
Set wsSht = .Sheets("GaebTesten.g42_2")
wsSht.Copy Before:=sThisBk.Sheets("Start")
Else
MsgBox "There is no sheet with name :US in:" & vbCr & .Name
End If
wbBk.Close SaveChanges:=False
End With
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Private Function SheetExists(sWSName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = Worksheets(sWSName)
If Not ws Is Nothing Then SheetExists = True
End Function
this is my second post here on stack overflow, and my first question was very dumb, and when I asked my first question, it was my 2nd hour with vba.
I think I am at about 30 hours now and I've learned a lot.
Question: I am doing this Excel Macro in VBA with userform too now. But mostly I google how to do what and I try to implement it WHILE understanding it, I don't just copy and paste code. Often I just do line by line and test it out.
BUT... how do you guys remember all that?
If I had to program the same thing again right now, I won't know how to, because I know how a syntax works, but I wouldn't know which syntax and stuff to actually use to achieve the desired effect...
Does it come from repeating the same things = experience?
Or how do you acquire the abilities to code without googling almost every single thing? When watching youtubers live streaming how they code something, they never look it up on the internet....
Let me present you a different way than pure string manipulation:
Set a new reference to Microsoft Scripting Runtime. This will enable the Scripting namespace. With it you can do things like the following:
sImportFile = "C:\StackFolder\PrintMyName.xlsx"
With New Scripting.FileSystemObject
Debug.Print .GetBaseName(sImportFile)
' Outputs "PrintMyName"
Debug.Print .GetExtensionName(sImportFile)
' Outputs "xlsx"
Debug.Print .GetFileName(sImportFile)
' Outputs "PrintMyName.xlsx"
Debug.Print .GetDriveName(sImportFile)
' Outputs "C:"
Debug.Print .GetParentFolderName(sImportFile)
' Outputs "C:\StackFolder"
End With
You can build a little helper function to give you the part of the file name you need:
Public Function GetFilenameWithoutExtension(ByVal filename as String) as String
With New Scripting.FileSystemObject
GetFilenameWithoutExtension = .GetBaseName(filename)
End With
End Function
and call it: sFile = GetFilenameWithoutExtension(sImportFile)
Regarding the interesting use of UBound in your subroutine, you could even get the filename (without extension) that way - assuming it doesn't contain additional dots:
vfilename = Split(sImportFile, "\")
sFile = vfilename(UBound(vfilename))
SplitName = Split(sFile, ".")
FilenameWithoutExtension = SplitName(UBound(SplitName)-1)
Extension = SplitName(UBound(SplitName))
These are, however, purely academical thoughts and I wouldn't recommend doing it this way.
Here are two ways to extract the workbook name without the file extension. Here I am removing the extension .xlsx. If the extension is constant, you can just hard code it. If not, you can use wildcards also
MsgBox Left(wbBk.Name, Len(ThisWorkbook.Name) - 5)
MsgBox Replace(wbBk.Name, ".xlsx", "")
You can refer to the sheet with the same name as the workbook by using something like
Sheets(Left(wbBk.Name, Len(ThisWorkbook.Name) - 5).Copy
Sheets(Replace(wbBk.Name, ".xlsx", "").Copy
You can use InstrRev. It is efficient as starts from the end of the string which is where the extension is located.
Left$(wbBk.Name, InStrRev((wbBk.Name, ".") - 1)

(VBA) Open Workbook from network drive

I have encountered a problem regarding the workbook.open function, when trying to open a workbook located on a network folder. The VBA macro leeds to an
"1004 Error"
without any specific reasons, only that the file path is not available.
I have used Google and this community for a very long time to solve this issue, below my steps I tried and my only solution at the end.
My question is: WHY does Excel behave like that and what can I do the next time?
Initially the user inputs the file path in a cell within the Source Workbook, saved locally on the computer. The VBA code take the input of the cell (I tried Range("K4") and also Range("K4").value) and aligns it to the string, which is visible (Variable Watch while Debugging) but failes when it comes to the Workbook.open function.
I tried to use the user specific network path (e.g. "G:/...") but also the Universal Network convention path ("\\xxx.xxx...") which is more accurate because not every user has mapped the network folder to the same drive letter.
At the end my only working solution was the hard coded path in the VBA editor with the UNC path.
Why is so? In this case the networkpath does not change, but when it comes to the moment where it is necessary that the folder must be written in a cell I will be lost.
Thank you for your feebdack!
EDIT:
Basically it's this code... I removed the unnecessary parts...
'Variablen
Dim MA$, Monat$, Fehltag$, Ort$, Projekt$, FilePlanung$, MainString$, NeuerString$
Dim LastRowM&, StartZelleP&, ProjektP&
Dim wb, wbP As Workbook
Dim wsK, wsS, wsM As Worksheet
Dim StartDatumM As Date
Dim array_monate As Variant
'Arbeitsblätter
Set wb = ThisWorkbook
Set wsK = wb.Sheets("Kopfblatt")
Set wsS = wb.Sheets("Stammdaten")
Set wsM = wb.ActiveSheet
'Fix
MA = wsK.Range("D2")
Monat = wsM.Name
FilePlanung = wsS.Range("K4")
Application.ScreenUpdating = False
Set wbP = Workbooks.Open(fileName:=FilePlanung)
'Set wbP = Workbooks.Open(FilePlanung) --> Tried also this and many other ways...
Set wsP = wbP.Sheets("aktuell")
This is the code I use:
Dim wb As Workbook
Set wb = Workbooks.Open(Worksheets("Sheet1").Range("A1").Value)

CountIf on a range from different workbook

I have been trying to find the root cause of this issue for a long time, but to no avail.
I am trying to count the number of instances a specific text occurs in another workbook (in this case the instance is "42.1" and the workbook name will be contained in Filename1). For some reason, when I execute the countif directly in the sheet, it yields to the correct answer (which should be 2). But whenever I run the code below, it gives me 3.
All the references appear OK since I manually called each value from another workbook and there was no issue. Could you please help ?
Please diregard CounttIfV, it is essentially equivalent to the application function CountIf and I can use both interchangeably.
'manually define the latest S&OP input file
filename = Application.GetOpenFilename
Shapes("DisplayFilename").TextFrame.Characters.Text = filename
'activate the S&OP Workbook
Filename1 = Split(filename, "\")(UBound(Split(filename, "\")))
Workbooks.Open (Filename1)
Workbooks(Filename1).Activate
'define the correct S&OP worksheet regardless of the date
For Each ws_mould In ActiveWorkbook.Worksheets
If ws_mould.Name Like "*Mould*" Then
Worksheets(ws_mould.Name).Activate
active_ws = ws_mould.Name
End If
Next ws_mould
Workbooks(Filename1).Activate
Set CellRange = Workbooks(Filename1).Worksheets(active_ws).Range(Worksheets(active_ws).Cells(27, 45), Worksheets(active_ws).Cells(53, 45))
'NumBlades = Application.WorksheetFunction.CountA(CellRange)
NumBlades = Module3.COUNTIFv(CellRange, "??42.1#*")
Shapes("DisplayFilename").TextFrame.Characters.Text = active_ws

Resources