trying to do in another focus with the window from the workbook from first trying to do in another focus with the window from the workbook from first
Sub Update_DHL()
Workbooks.Open Filename:=trk
Workbooks.Open Filename:=stp
Workbooks.Open Filename:=dhl
Windows(stp).Activate
Workbooks(stpfile).Activate
Range("B2").Select
ActiveCell.Formula = _
"Hi"
Range(Cells(2, 2), Cells(2, 2)).Copy
'Range(Cells(3, 2), Cells(65536, 45)).Select
'Selection.ClearContents
'Range(Cells(3, 47), Cells(65536, 74)).Select
'Selection.ClearContents
' Set wb = Workbooks("VMW Macro.xlsm") 'Name of the workbook you are copying from
' Set ws = wb.Sheets("Extract") 'Name of sheet you are copying
' DateStamp = Format(Now(), "mm-dd-yyyy hhmmss")
End Sub
Make sure you define variables for your workbooks and worksheets properly. You can then use them for your Range and Cells objects to specify in which workbook and worksheet they are. This way you don't need .Activate or .Select because the code even works if the workbook has no focus.
Make sure in your entire code there is no Range and Cells object without a workbook and worksheet specified. Either by using a variable like shown below. Or directly like ThisWorkbook.Worksheets("Sheet1").Range(…).
You only need to .Activate or .Select if you want to focus it for the user. You never need to do this to make VBA work properly (VBA can work with non-focused workbooks/worksheets).
Option Explicit
Sub Update_DHL()
'open your workbooks
On Error GoTo ERR_WB_OPEN
Dim wbTrk As Workbook
Set wbTrk = Workbooks.Open(Filename:=[truckfilePath])
Dim wbStp As Workbook
Set wbStp = Workbooks.Open(Filename:=[stopfilePath])
Dim wbDhl As Workbook
Set wbDhl = Workbooks.Open(Filename:=[dhlfilePath])
On Error GoTo 0
'define in which worksheet in those workbooks you want to work
Dim wsTrk As Worksheet
Set wsTrk = wbTrk.Worksheets("SheetName")
Dim wsStp As Worksheet
Set wsStp = wsStp.Worksheets("SheetName")
Dim wsDhl As Worksheet
Set wsDhl = wsDhl.Worksheets("SheetName")
'now work with those worksheets directly (no activate or select needed!)
wsStp.Range("B2").Formula = "=IF(SUMIF('Route Master.xls'!$C$7:$C$65536,$A2,'Route Master.xls'!$Q$7:$Q$65536)>0,TRUE,FALSE)"
wsStp.Range("B2").Copy
wsStp.Range(wsStp.Cells(2, 2), wsStp.Cells(EndRow2, 2)).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
' note this code does not work because `EndRow2` is nod defined
'select and activate a specific workbook/worksheet
'you do this ONLY if you want to focus it for the USER. Never do this for VBA instead work directly with the worksheets as shown above.
wbDhl.Activate
wsDhl.Select
Exit Sub
ERR_WB_OPEN:
MsgBox "One of the files could not be loaded.", vbCritical
End Sub
Don't forget to close your workbooks wbDhl.Close SaveChanges:=True/False otherwise they stay open.
See below. You can reference the workbook directly as pointed out by BigBen. In code, you never need to select ranges or activate workbooks/worksheets. You just need to reference them directly.
Notice I also added explicit declaration of types.
Dim a, b As Long
The line above will declare a as a variant and b as long
Sub Update_DHL()
Dim trk As Workbook, stp As Workbook, dhl As Workbook, wb As Workbook, wbNew As Workbook
Dim ws As Worksheet
Dim stpfile As String, DateStamp As String, strFolderpath As String
Dim EndRowTrk As Long, EndRowStp As Long, EndRowDHL As Long
Dim fileExplorer As FileDialog
Set dhl = [dhlfilePath]
Set trk = [truckfilePath]
Set stp = [stopfilePath]
stpfile = stp
Workbooks.Open Filename:=trk
Workbooks.Open Filename:=stp
Workbooks.Open Filename:=dhl
With Workbooks(stpfile).Worksheets(1)
.Range("B2").Formula = "Hi"
End With
End Sub
Related
I want to be able to select a workbook and then copy the content from that workbook (sheet 1) into my current active workbook where I run the macro. I've been looking at some answers here on StackOverflow to similar questions and got the following code (see below).
The selection of a file is currently working fine, but when I run the macro it throws an error
Runtime error "438": Object does not support that method or property`
(please note, that the error comes in my native language and is just translated by me)
Sadly no object is marked that he relates to, so I can't really make out what problem he has. Yet, I guess it is a problem with the PasteSpecial in the last line of function GetTemplateData, but that code should be alright (what is it supposed to do? Save the data into the first sheet of the give workbook activeWorkbook) and pass the reference back go GeneratedValues-routine.
Option Explicit
Private Sub GenerateValues()
'Application.ScreenUpdating = False
'Application.DisplayAlerts = False
Dim activeWorkbook As Workbook
Dim activeWorksheet As Worksheet
Set activeWorkbook = Application.activeWorkbook
Set activeWorksheet = GetTemplateData(activeWorkbook)
activeWorkbook.Save
End Sub
'Get The Template Data
Private Function GetTemplateData(activeWorkbook As Workbook) As Worksheet
Dim templateWorkbook As Workbook
'Grab the Template Worksheet
Set templateWorkbook = UseFileDialogOpen
'Select all Content
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Copy
'activeWorkbook.Sheets(activeWorkbook.Sheets.Count).Range("A1", Cells.End(xlDown) & Cells.End(xlRight)).PasteSpecial xlPasteValues
activeWorkbook.Sheets(1).Range("A1", Cells.End(xlDown) & Cells.End(xlRight)).PasteSpecial xlPasteValues
End Function
'From https://learn.microsoft.com/de-de/office/vba/api/excel.application.filedialog
'Select the Workbook containing the Exported Template-Stories by User Selection
Function UseFileDialogOpen() As Workbook
Dim lngCount As Long
Dim filePath As String
Dim templateBook As Workbook
' Open the file dialog
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
Set templateBook = Workbooks.Open(.SelectedItems(1))
' Display paths of each file selected
'For lngCount = 1 To .SelectedItems.Count
' MsgBox .SelectedItems(lngCount)
'Next lngCount
End With
templateBook
End Function
I believe all of your problems originate here:
Private Sub GenerateValues()
'Application.ScreenUpdating = False
'Application.DisplayAlerts = False
Dim activeWorkbook As Workbook
Dim activeWorksheet As Worksheet
Set activeWorkbook = Application.activeWorkbook
Set activeWorksheet = GetTemplateData(activeWorkbook)
activeWorkbook.Save
End Sub
ActiveWorkbook is a defined "variable" in VBA, so it is confused as to why you are trying to reassign it. Try using a different variable name instead.
Note: although ActiveWorksheet is not a defined variable in VBA, it is close in name to ActiveSheet, so I would also change that variable name to something different just so to not confuse you when writing future code.
You could try something similar to this:
Sub CopyContentsFromOtherWorkbook()
Dim wb As Workbook
Dim twb As Workbook
filePath = "C:\File.xlsx"
Set wb = Workbooks.Open(filePath)
wb.Sheets(1).Range("A1:Z10000").Copy
Set twb = ThisWorkbook
twb.Sheets(1).Range("C1").PasteSpecial xlPasteValues
wb.Close
twb.Save
End Sub
I'm having an issue with the above: I am using the answer provided, but still hitting an object error. Can you see what i'm missing? I hit the errror at "Cash_Sheet.Range("C8").PasteSpecial xlPasteValues"
`Sub Refresh_Cash()
Dim Morning_Export As Workbook
Dim Cash_Sheet As Worksheet
'Open MorningExport cash workbook
Set Morning_Export = Workbooks.Open(Range("varMornExpPath"))
'Copy cash from Morning_Export_Settlement_Cas tab:
Morning_Export.Sheets("Morning_Export_Settlement Cas").Range("A1:AR5000").Copy
'Set the sheet in this file to paste to:
Set Cash_Sheet = ThisWorkbook.Worksheets("Cash")
'Clear prior data from EOD_Check
Cash_Sheet.Range("rngRefreshPFMExp").ClearContents
'EVERYTHING WORKS UP UNTIL THIS POINT BUT THEN FAILS HERE
Cash_Sheet.Range("C8").PasteSpecial xlPasteValues
'Close MorningExport book:
Morning_Export.Close
End Sub
Sub Refresh_Cash()
Dim wb As Workbook: Set wb = Workbooks.Open(Range("varMornExpPath"))
Dim cs As Worksheet: Set cs = ThisWorkbook.Sheets("Cash")
cs.Range("rngRefreshPFMExp").ClearContents
wb.Sheets("Morning_Export_Settlement Cas").Range("A1:AR5000").Copy
cs.Range("C8").PasteSpecial xlPasteValues
wb.Close
End Sub
Instead of using copy\paste you can directly write the values from one range in to another. This works much faster on large data sets because it doesn't have to copy twice. It also results in cleaner code.
Public Sub Refresh_Cash()
Dim Morning_Export As Workbook
Dim Cash_Sheet As Worksheet
'Open MorningExport cash workbook
Set Morning_Export = Workbooks.Open(ActiveSheet.Range("varMornExpPath"))
'Set the sheet in this file to paste to:
Set Cash_Sheet = ThisWorkbook.Worksheets("Cash")
' Set the values directly
Cash_Sheet.Range("C8") = Morning_Export.Sheets("Morning_Export_Settlement Cas").Range("A1:AR5000")
'Close MorningExport book:
Morning_Export.Close
End Sub
SEE: Copy/PasteSpecial vs Range.Value = Range.Value
I have to 2 Excel workbooks to work with: Book1october & Book2. Book1october18 is an import file, meaning that it changes monthly, along with the name (next month it will be Book1november18). I have to copy some data from Book1october to Book2 automatically through VBA code.
This is the code that I've written:
Windows("Book1october18").Activate
Sheets("Sheet1").Activate
Range("B2:AQ5").Select
Selection.Copy
Windows("Book2").Activate
Sheets("Sheet1").Activate
Range("R2:BG5").Select
ActiveSheet.Paste
My problem is that I don't know how to write the code in order to make the actions that I want whenever the month's name changes and also the year. (I have to make it for all the months and 2019)
You can automatically update your workbook name using the Date() function and Format()
Dim sWbName As String
sWbName = "Book1" & LCase(Format(Date, "mmmmyy"))
Debug.Print sWbName
'Prints Book1october18
The name/path of the workbook doesn't need to matter. Use K.Davis's code to come up with a filename, or prompt the user for a path/file to open - get that string into some sourceBookPath variable, then have the macro open the workbook. Now you can hold a reference to that Workbook object:
Dim sourceBook As Workbook
Set sourceBook = Application.Workbooks.Open(sourceBookPath)
Now, the worksheet.
Dim sourceSheet As Worksheet
If the sheet is always going to be named "Sheet1", then you can do this:
Set sourceSheet = sourceBook.Worksheets("Sheet1")
Or, if the sheet is always going to be the first sheet in the book (regardless of its name), you can do this:
Set sourceSheet = sourceBook.Worksheets(1)
Once you have a Worksheet object, you can get the Range you need - but first you need your target. Again if "book2" is opened by the macro, things are much simpler:
Dim targetBook As Workbook
Set targetBook = Application.Workbooks.Open(targetBookPath)
Or is it created by the macro?
Set targetBook = Application.Workbooks.Add
Anyway, we want the first sheet:
Dim targetSheet As Worksheet
Set targetSheet = targetBook.Worksheets(1)
And now we can copy from the source, and paste to the target:
sourceSheet.Range("B2:AQ5").Copy targetSheet.Range("R2:BG5")
And not once did we ever need to .Select or .Activate anything, and we never needed to care for any Window.
Replace:
Windows("Book1october18").Activate
with:
s = LCase(Format(Now, "mmmm")) & Right(Year(Now), 2)
Windows(s).Activate
Try this.
This is a recognition of the next month's document, assuming you have opened two documents.
Sub test()
Dim Wb1 As Workbook, wb2 As Workbook
Dim Wb As Workbook
For Each Wb In Workbooks
If InStr(Wb.Name, "Book1") Then
Set Wb1 = Wb
ElseIf InStr(Wb.Name, "Book2") Then
Set wb2 = Wb
End If
Next Wb
Wb1.Sheets("Sheet1").Range("B2:AQ5").Copy wb2.Sheets("Sheet1").Range("r2")
End Sub
New VBA user here, thank you for your patience. I want to copy and paste as values a range from a single closed worksheet to an active worksheet. Specifically, I want to use VBA in an active workbook to copy range A1:HW6000 from the "AllData" tab in TOOL.XLSM while TOOL.XLSM is closed and paste into the active workbook in range A1:HW6000 in the active sheet as values.
I have code that will do this (care of Peh at stackoverflow, thank you Peh!), but the code runs forever (more than 45 minutes), because running the code seems to recalculate both the new workbook and the import workbook at the same time, and the import workbook (TEST.xslm) is very large. I am running on a Mac. Here is the code I currently have:
Sub ImportData()
Dim App As New Excel.Application 'create a new (hidden) Excel
' remember active sheet
Dim wsActive As Worksheet
Set wsActive = ThisWorkbook.ActiveSheet
' open the import workbook in new Excel (as read only)
Dim wbImport As Workbook
Set wbImport = App.Workbooks.Open(Filename:="/Users/cwight/Desktop/TOOL.xlsm", UpdateLinks:=True, ReadOnly:=True)
'copy the data of the import sheet
wbImport.Worksheets("AllDATA").Range("A1:HW6000").Copy
wsActive.Range("A1").PasteSpecial Paste:=xlPasteFormats 'paste formats
wsActive.Range("A1").PasteSpecial Paste:=xlPasteValues 'paste values
App.CutCopyMode = False 'clear clipboard (prevents asking when wb is closed)
wbImport.Close SaveChanges:=False 'close wb without saving
App.Quit 'quit the hidden Excel
End Sub
Can I integrate the following bits of code to turn off the calculation during the import process? If so, how exactly? I cannot figure it out:
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Is there anything else I can do? Thank you tremendously for your time.
here it's a function that use vectors for copy data from one excel to another, make sure to assign this to a button and into a cell to specify the path.
create a module named : "FUNCTIONS" and paste this over there :
Function range_to_variant(variant_arr As Variant, sheet As Worksheet, first_range As String, last_column As String, last_row_column As String)
variant_arr = sheet.Range(first_range & ":" & last_column & sheet.Cells(sheet.Rows.Count, last_row_column).End(xlUp).Row).Value
End Function
Function array_to_range(variant_arr As Variant, sheet As Worksheet, first_range As String)
'example
' Call array_to_range(new_variant, Worksheets("Sheet1"), "1.1")
Dim split_arr() As String
split_arr = Split(first_range, ".")
Dim range1 As String
Dim range2 As String
Dim range3 As String
Dim range4 As String
range1 = Replace(sheet.Cells(CInt(split_arr(0)), CInt(split_arr(1))).Address, "$", "")
range2 = Replace(sheet.Cells(CInt(split_arr(0)) + UBound(variant_arr, 1) - 1, CInt(split_arr(1)) + UBound(variant_arr, 2) - 1).Address, "$", "")
sheet.Range(range1 & ":" & range2).Value = variant_arr
sheet.Range(range1 & ":" & range2).Columns.AutoFit
End Function
After you are done create 2 sub in which write this :
Sub select_fle2()
Call Select_file("b10", "xlsm")
End Sub
Sub Run()
Dim xl As New Excel.Application
xl.Workbooks.Open (Worksheets("MAIN").Range("B7").Value)
xl.Visible = False
Dim raw_data As Variant
Call range_to_variant(raw_data, xl.Worksheets("your_sheet_name"), "A1", "HW", "A")
xl.Quit
Set xl = Nothing
ThisWorkbook.Worksheets("sheet_paste").Columns("A:HW").ClearContents
Call array_to_range(raw_data, Worksheets("sheet_paste"), "1.1")
End sub
What I need is a way to send the contents of some cells in "ThisWorkbook" (where the macro is) to a specific sheet in another workbook (the location of which will not change, unlike "ThisWorkbook")
for some reason, this below dosen't work:
Sub Transplant()
Dim thispath As String
Dim targetpath As String
'Set filepaths
thispath = ThisWorkbook.FullName
targetpath = ThisWorkbook.Path & "/subdir/Targetbook.xlsm"
Dim Srcwb As Workbook
Dim Trgwb As Workbook
'Set workbooks
Set Srcwb = Workbooks.Open(thispath)
Set Trgwb = Workbooks.Open(targetpath)
Srcwb.Worksheets("Sheet1").Range(Srcwb .Worksheets("Sheet1").Range("A1"), _
Srcwb.Worksheets("Sheet1").Range("A1").End(xlToRight)).Copy _
Destination:=Trgwb.Sheets("Sheet1").Cells(1, 1)
End Sub
Please help!
//Leo
This is pretty much the same as what you've got, although I didnt re-open the active workbook.
Can you describe the range you're trying to copy? You might find that UsedRange is easier.
Sub Transplant()
Dim DWB As Workbook
Dim S As Worksheet
Set S = ThisWorkbook.WorksheetS("Sheet1") ' forgot to rename Source to S
Set DWB = Application.Workbooks.Open(Thisworkbook.Path & "/subdir/Targetbook.xlsm")
Set D = DWB.Worksheets("Sheet1")
S.Range(S.Range("A1"), S.Range("A1").End(xlToRight)).Copy Destination:=D.Cells(1,1)
' S.UsedRange.Copy Destination:=D.Cells(1,1) - this might be easier
End Sub