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"))
Related
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
So i am using Opendateabase method in Ms Access to read the worksheet of a Excel workbook. Why do i get multiple entries for worksheets when I can only see one excel worksheet when i open the file.
So the system used to just import the excel workbook without checking the column names which meant after waiting 5-10mins of importing if the user didnt name his columns correctly the program would crash. I want this to check the column names before it imports which means VBA needs to know the name of the worksheet its importing.
Set db = OpenDatabase(Me.Text2.Value, True, False, "Excel 8.0")
For Each tbl In db.TableDefs
MsgBox tbl.Name 'Would be where the sheet name is picked
Next
db.Close
Set rstbl = CurrentDb.OpenRecordset("SELECT * FROM ImportColumnNames")
S = "SELECT * FROM [Excel 8.0;HDR=Yes;Database=" _
& Me.Text2 & "].[" & SheetName & "$] WHERE False;"
Now seeing as the file only has one worksheet called CLENAS i was expecting 1 answer however i got Sheet1$, CLENAS, CLENAS$ now i know it should be CLENAS but how do i make sure that VBA picks the right one.
Found the answer here: Read Excel file sheet names
Dim objExc As Object ' late
Dim objWbk As Object ' late
Dim objWsh As Object ' late
'Set objExc = New Excel.Application ' early
Set objExc = CreateObject("Excel.Application") ' late
Set objWbk = objExc.Workbooks.Open(pWorkBook)
For Each objWsh In objWbk.Worksheets
Debug.Print objWsh.Name
Next
Set objWsh = Nothing
objWbk.Close
Set objWbk = Nothing
objExc.Quit
Set objExc = Nothing
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)
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.
First time poster here. I've been reading tutorials/guides all day and made a lot of strides, but am having a tough time figuring out how to write a macro that does what I want to do.
I get around 100 time sheets per week that are then copied and imported into an accounting software. The sheets are all based off of a template, are in separate workbooks, and have a worksheet titled "Pre Import Time Card" within them. I copy the values from each book's pre import worksheet into a new file and upload them to our accounting software as a batch.
I want to have a macro open each file automatically, copy the range A1:I151 on each workbook, and then paste the values into a new worksheet. Because of the import templates design, this inevitably leads to many blank rows within the specified range. I would like to delete any blank rows as a final step.
UPDATE: I HAVE COPIED THE CODE TO REFLECT WHAT I CURRENTLY HAVE.Also a list of new problems is below.
pasting to next unused row is not working
I need to figure out how to kill the old file / not have it enter the same file twice.
I would like to suppress the "Privacy warning on VBA / Active X controls" dialog that comes up at each save.
It's not currently copying correctly. I'm getting a bug at the rDest.Resize line.
Object variable or With Block Variable not set.
I had it running when using file names in an array, but decided that was unnecessary and to use a For.. Each loop.
Sub CopySourceValuesToDestination()
Dim wbDest As Workbook
Dim wbSource As Workbook
Dim sDestPath As String
Dim sSourcePath As String
Dim aFile As String
Dim shDest As Worksheet
Dim rDest As Range
Dim i As Long
Dim TSSize As Object
Dim objFso As Object 'New FileSystemObject
Dim objFolder As Object 'Folder
Dim objFile As Object 'File
Set objFso = CreateObject("Scripting.FileSystemObject")
sDestPath = "Z:\Dropbox\My Documents\TimeSheets\Processed\"
sSourcePath = "Z:\Dropbox\My Documents\TimeSheets\Copying\"
'Open the destination workbook at put the destination sheet in a variable
Set wbDest = Workbooks.Open(sDestPath & "Destination.xlsm")
Set shDest = wbDest.Sheets(1)
Set objFolder = objFso.GetFolder(sSourcePath)
For Each objFile In objFolder.Files
aFile = objFile.Name
Set objWb = Workbooks.Open(sSourcePath & aFile)
'find the next cell in col A
Set rDest = shDest.Cells(xlLastRow + 1, 1)
'write the values from source into destination
TSSize = wbSource.Sheets(4).Range("A1").End(xlDown).Row
rDest.Resize(TSSize, 9).Value = wbSource.Sheets(4).Range("A1:I" & TSSize).Value
wbSource.Close False
wbDest.SaveAs sDestPath & "Destination.xlsm"
wbDest.Close
Kill sSourcePath & wbSource
Next
End Sub
Function xlLastRow(Optional WorksheetName As String) As Long
' find the last populated row in a worksheet
If WorksheetName = vbNullString Then
WorksheetName = ActiveSheet.Name
End If
With Worksheets(1)
xlLastRow = .Cells.Find("*", .Cells(1), xlFormulas, _
xlWhole, xlByRows, xlPrevious).Row
End With
End Function
Provded your datarange in the time sheet is continuous you can replace
rDest.Resize(151,9).Value = wbSource.Sheets(1).Range("A1:I151").Value
with
var for storing
dim TSsize as long
TSsize = wbSource.Sheets(1).Range("A1").end(xlDown).Row
rDest.Resize(TSsize,9).Value = wbSource.Sheets(1).Range("A1:I" & TSsize).Value
This is prevent the empty rows from getting into your sheet in the first place.
If the each time sheet is not a continuous range you can interate through the rows looking for empty rows and deleting them. Let me know if that is the case and i will update my answer.