So I'm using this macro to extract only the data that I need to perform a regression, and the sample set includes quite a bit of useless information for my needs. When I try to select the columns from the CCDetail workbook- I get the "'Range' of object '_Global' Failed" error. Any ideas on why this is?
Sub ExtractCCDetail()
Dim WorkbookName As String
Dim CCDetail As Workbook
Dim Harvester As Workbook
Dim RAWData As Worksheet
Set CCDetail = Workbooks(2)
Set Harvester = ThisWorkbook
WorkbookName = CCDetail.Name
CCDetail.Activate
Set RAWData = Worksheets("Department Totals")
RAWData.Select
'This is where the code will break
Range( _
"D:D,E:E,F:F,M:M,X:X,Y:Y,Z:Z,AA:AA,AC:AC,AD:AD,AE:AE,AF:AF,BD:BD,BF:BF," _
).Select
Selection.Copy
Harvester.Activate
Sheets.Add After:=Sheets(Worksheets.Count), Count:=1
ActiveSheet.Name = WorkbookName
ActiveSheet.Paste
End Sub
*As a side note- I have tested doing this manually and I don't have a problem. I have also tried calling
ActiveSheet.Range (wanted Range)
RAWData.Range (wanted range)
But neither of these have worked.
The problem is that you have an extra comma in the arguments for your Range. Try this instead:
Range("D:D,E:E,F:F,M:M,X:X,Y:Y,Z:Z,AA:AA,AC:AC,AD:AD,AE:AE,AF:AF,BD:BD,BF:BF").Copy
If you want to clean up your code a bit and avoid Selects and such, try this out:
Sub ExtractCCDetail()
Dim WorkbookName As String
Dim CCDetail As Workbook
Dim Harvester As Workbook
Dim RAWData As Worksheet
Set CCDetail = Workbooks(2)
Set Harvester = ThisWorkbook
WorkbookName = CCDetail.Name
Set RAWData = CCDetail.Worksheets("Department Totals")
RAWData.Range("D:D,E:E,F:F,M:M,X:X,Y:Y,Z:Z,AA:AA,AC:AC,AD:AD,AE:AE,AF:AF,BD:BD,BF:BF").Copy
Dim wksCopy As Worksheet
Set wksCopy = Harvester.Sheets.Add(After:=Sheets(Worksheets.Count), Count:=1)
With wksCopy
.Paste
.Name = WorkbookName
End With
End Sub
Related
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
I need to resize excel particular column in a particular sheet.But not able to do so
Sub resizeColumn(sourceWb As String, Sheet As String, column As String)
Dim wkbSource As Workbook
Dim sheetName As Worksheet
Dim columnname As String
Application.ScreenUpdating = False
Set wkbSource = Workbooks.Open(sourceWb)
Set sheetName = wkbSource.Sheets(Sheet).Activate
Worksheets("Column width").Range("A5").ColumnWidth = 16
wkbSource.Close SaveChanges:=True
wkbSource.Close
End Sub
I think the problem is that you are mixing the names and objects.
I assume from your code that you would like to call this with this manner:
Sub CallResizeColumn()
Call ResizeColumn("PathToYourWorkbook.xlsm", "SheetToResize", "A5")
End Sub
I have changed a bit your notation by adding a p at the beginning of your parameters (I think it is not a good practice to call them very similar to the keywords).
Please keep in mind that you need to use the full reference to your range ("workbook.worksheet.range").
(Note: when you turn off the SreenUpdating, be sure that you turning it back.)
Private Sub ResizeColumn(pSourceWb As String, pSheet As String, pColumn As String)
Dim wkbSource As Workbook
Dim shSheet As Worksheet
Dim rngColumn As Range
'Application.ScreenUpdating = False
Set wkbSource = Workbooks.Open(pSourceWb)
Set shSheet = wkbSource.Sheets(pSheet)
Set rngColumn = shSheet.Range(pColumn)
rngColumn.ColumnWidth = 16
'wkbSource.Close SaveChanges:=True
wkbSource.Close
End Sub
I'm trying to delete a worksheet from MS Access.
There's a lot of data on the sheet, including two charts. Instead of trying to delete all the data, I want to delete the sheet and re-add it.
I've looked up several ways to delete a sheet with MS Access and found the following .delete as the easiest, but it doesn't work. The "if not" works and goes through the .delete statement, but the .add(after...) fails.
I obviously have something wrong and any input is appreciated.
Dim wkb as excel.workbook
Dim wksheetname as excel.worksheet
Dim strsheetname as string
wkb.Activate
On Error Resume Next
Set wksSheetName = wkb.Sheets(StrSheetName)
On Error GoTo 0
If Not wksSheetName Is Nothing Then
wkb.Sheets(StrSheetName).Delete
Set wksSheetName = Nothing
End If
wkb.Sheets.Add(After:=wkb.Sheets(wkb.Sheets.Count)).Name = StrSheetName
Set wksSheetName = wkb.Sheets(StrSheetName)
This somewhat simpler method works here:
Const WorksheetName As String = "Sheet2"
Dim Workbook As Excel.Workbook
Dim Worksheet As Excel.Worksheet
Set Workbook = ThisWorkbook
For Each Worksheet In Workbook.Worksheets
If Worksheet.Name = WorksheetName Then
Worksheet.Delete
Exit For
End If
Next
Set Worksheet = Workbook.Worksheets.Add(After:=Workbook.Worksheets(Workbook.Worksheets.Count))
Worksheet.Name = WorksheetName
I'm having trouble with renaming a worksheet in VBA.
I'm writing a Sub that needs to check if there is a worksheet in the workbook that has a specific name, and if there isn't then make a new sheet with this name.
I get the runtime error 1004 application defined or object defined error. I'm hoping anyone can help me. Here is my code:
Dim ws As Worksheet
Dim ArrayElement As Variant
Dim Current_Tabs(1 To 10) As String
NumberNewTab = 1
Tab_Name_Current_Game = Echt_team1 + "vs. " + Echt_team2
For Each ws In Worksheets 'For every worksheet in this workbook
Found = False
For Each ArrayElement In Current_Tabs array
If Tab_Name_Current_Game = ArrayElement Then
Worksheets(ws).Activate
Worksheets.Select
Found = True
End If
Next ArrayElement
If Found = False Then
Worksheets.Add
Sheets(1).Name = Tab_Name_Current_Game **'Here I get the error**
Current_Tabs(NumberNewTab) = Tab_Name_Current_Game
NumberNewTab = NumberNewTab + 1
End If Next ws
If I use Sheets(1).Name = "Test" then I don't run into errors. I don't get why this would be a problem for VBA. Hoping someone can help me. Thank you!
You never defined Tab_Name_Current_Game.
Add Dim Tab_Name_Current_Game as String to your declarations at the top. Then see what happens.
You can make it much easier:
Public Sub renameSheet()
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim Tab_Name_Current_Game As String
Set wb = Excel.ActiveWorkbook
'The line below is copied from your code, but I don't like it.
'You should pass Echt_team1 and Echt_team2 as input parameters to this Sub.
Tab_Name_Current_Game = Echt_team1 + "vs. " + Echt_team2
On Error Resume Next
Set ws = wb.Worksheets(Tab_Name_Current_Game)
On Error GoTo 0
If ws Is Nothing Then
Set ws = wb.Worksheets.Add
ws.Name = Tab_Name_Current_Game
End If
End Sub
To make the code more reliable, you can also add this function to your code: Function to check if sheet name is valid, and change this line:
ws.Name = Tab_Name_Current_Game
to
ws.Name = legalSheetName(Tab_Name_Current_Game)
It will ensure that the name you are trying to assign to a worksheet is not too long and has no illegal characters.
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