VBA - Pulling specific data from QueryTables - vba

I am currently using Excel 2011 on Mac, and I am trying to pull data using a QueryTable, but I am forced to have to import the entire table. I am currently pasting the entire table onto a hidden sheet, then using a formula to pull data from the specific cell. To show you what I mean, Here is a sample:
Sub Yield()
Dim URL As String
Dim qt as QueryTable
Dim hs As Worksheet
Set hs = Worksheets("Hidden Sheet")
Set ws = Worksheets ("Managed Equity Portfolios")
URL = "http://www.nasdaq.com/symbol/spy"
Sheets("Hidden Sheet").Visible = True
Set qt = hs.QueryTables.Add( _
Connections:= "URL;" & URL, _
Destination:= hs.Range("A1"))
qt.RefreshStyle = xlOverwriteCells = True
qt.BackgroundQuery = True
qt.SaveData = True
qt.Refresh Background Query:= False
'I am using the same parameters here as my other code, honestly not
'sure why a lot of it is on here, but I kept it because it works.
Worksheets("Hidden Sheet").Visible = False
End Sub
Currently, the information I need is being pasted into the Hidden Sheet in cell B42. I made it so the cell that I want the information ='Hidden Sheet!'B42 but this doesn't seem very efficient. Is there any way I could have just the cell B42 be put into Excel?
I'll be on here to clear up any questions, thank you so much!

Related

Loop and Paste special

I'm copying values as part of one sub process and pasting value through an update button on userform.
To copy values:
Private Sub Month1_Click()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.AskToUpdateLinks = False
Dim wkb As Workbook
Dim wks As Worksheet
Set wkb = Workbooks.Open("Place on drive")
Set wks = wkb.Sheets("Training1")
wks.Range("Start:Finish").Copy
wkb.Close
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
Application.ScreenUpdating = True
End Sub
To paste values in current sheet:
Private Sub UpdateActuals_Click()
For i = 1 To 12
If Me.Controls("Month" & i).Value = True Then
ThisWorkbook.Sheets("2017 Actuals").Range(i+1, 5).PasteSpecial xlPasteValues
End If
Next i
End Sub
If I replace "i+1, 5" with "B5", it errors with
"PasteSpecial method of Range class failed".
I feel as if values copied in one sub process are not brought to second one, would that be correct?
Also, how do I reduce processing time given that I have 12 months (12 files) in various places that I can't change the location for...
Range usually likes a starting cell and an ending cell. I suggest since you are looking at just one cell that you change .Range to .Cells. If you really want to use a range with RC format, .Range(Cells(row1, col1), Cells(row2, col2)), if you want just one cell then you can make the two parts the same. I have run into problems before using Range and only one cell definition before, either make it .Cells for your target or fill out Range the way I have explained.. Cheers.
Dim 2017actWS AS Worksheet
Set 2017actWS = ThisWorkbook.Worksheets("2017 Actuals")
1)
2017actWS.Cells(i+1, 5).PasteSpecial xlPasteValues
-or-
2)
2017actWS.Range(2017actWS.Cells(i+1, 5), 2017actWS.Cells(i+1,5)).PasteSpecial xlPasteValues
When using Ranges excel will often throw errors if they are not the same size in a copy and paste, you can eliminate that by using a single cell as the starting target of your paste with .Cells
Also I don't see you call your function. You will want your paste close to your copy or you might find things get strange (suggestion: just after your copy).
Edited to be sure there is not worksheeet ambiguity. Thank you Scott C.
Cheers, WWC

Excel VBA - Export a copy of current workbook

The Task
I am working on a chart generator from a data sheet. As part of my spec, I need to be able to extract this chart into its separate workbook.
My Functions
This is the function I currently have:
Sub EWbtn()
'''Extract Worksheet Button Function
Dim OriginalWB As Workbook, NewCRCWB As Workbook
Set OriginalWB = ThisWorkbook
Set NewCRCWB = Workbooks.Add
OriginalWB.Sheets("Generator").Copy Before:=NewCRCWB.Sheets("Sheet1")
OriginalWB.Sheets("Module Part Number Tracker").Copy Before:=NewCRCWB.Sheets("Generator")
OriginalWB.Sheets("CRC").Copy Before:=NewCRCWB.Sheets("Module Part Number Tracker")
Application.DisplayAlerts = False
NewCRCWB.Worksheets("Generator").Visible = False
NewCRCWB.Worksheets("Module Part Number Tracker").Visible = False
NewCRCWB.Worksheets("Sheet1").Delete
Application.DisplayAlerts = True
End Sub
I copy through the 2 sheets from which the data for the chart is used, and make them hidden in the new workbook. The CRC sheet has quite a few macros that are run on the chart and can also be called via buttons on the chart. For example this function is for a button which hides 5 columns of data on the chart:
Public Function SHGSbtn()
'''Show Hides Gateway Stages Function
Dim wsCRC As Worksheet
Set wsCRC = Worksheets("CRC")
If wsCRC.Buttons("SHGateway").Caption = "Hide Gateway Stages" Then
Range(Cells(9, 9), Cells(9, 13)).EntireColumn.Hidden = True
wsCRC.Buttons("SHGateway").Caption = "Show Gateway Stages"
ElseIf wsCRC.Buttons("SHGateway").Caption = "Show Gateway Stages" Then
Range(Cells(9, 9), Cells(9, 13)).EntireColumn.Hidden = False
wsCRC.Buttons("SHGateway").Caption = "Hide Gateway Stages"
End If
End Function
My Issue
The workbook copies over with no errors, however when i try and use one of the buttons, it uses the code in the original workbook, even if its closed it will open up the original workbook. Anyone know why this is and how do I get around it?

Modifying ActiveX controls through custom add-in in Excel

I'm working on moving a worksheet into an add-in so I can make updates to the code without having to give new workbooks to everyone. The process has been fairly straightforward until I got to the area where add-in code needs to modify ActiveX controls present on the sheet.
The previous code I was using to modify these:
If Sheet1.Range(RowHighlightToggle.LinkedCell).Value = True Then
RowHighlightToggle.Caption = "Row Highlight - On"
HighlightStatus = 0
Else
RowHighlightToggle.Caption = "Row Highlight - Off"
HighlightStatus = 1
End If
RowHightlightToggle being the ActiveX control in question. I'm not sure how to refer to this button when coding inside the add-in. I've tried doing Sheet1.RowHighlightToggle.LinkedCell and that is giving me an error as well. I'm not using Sheet1 inside the add-in as I have a function to get codenames from the target workbook so Sheet1 is usually something like AWSheet1 but it is a Worksheet variable so that is not the issue either. I can read the linked cell value quite easy but I have no way of changing the button caption without somehow referring to the button inside the code.
This button will always be present in the workbook that this add-in is being made for, I have additional code to make sure the add-in is only visible in that workbook as well and hides itself for any others.
Is there a way to refer to the button through the add-in or possibly a way to link the caption to a cell so I can change the cell value to update the caption?
After a bit more research I found out I can refer to it by using OLEObjects, working code including the rest of the sub is below.
Sub RowHighlightToggle()
'-----Startup Code--------
With Application
.ScreenUpdating = False
.DisplayStatusBar = False
.DisplayAlerts = False
End With
'------------------------
Dim HighlightStatus As Long, AWSheet1 As Worksheet, ThisButton As Object
If TargetWorkbook Is Nothing Then Set TargetWorkbook = ActiveWorkbook
Set AWSheet1 = GetWsFromCodeName(TargetWorkbook, "Sheet1")
Set ThisButton = AWSheet1.OLEObjects("RowHighlightToggle")
Call Common_Functions.StartUnlock
If AWSheet1.Range(ThisButton.LinkedCell).Value = True Then
ThisButton.Object.Caption = "Row Highlight - On"
HighlightStatus = 0
Else
ThisButton.Object.Caption = "Row Highlight - Off"
HighlightStatus = 1
End If
Call Common_Functions.StartLock
If Worksheets.Count > 6 Then
Call Common_Functions.SheetArrayBuild(TargetWorkbook)
For i = LBound(SheetArray) To UBound(SheetArray)
Sheets(SheetArray(i, 1)).Range("Z1").Value = HighlightStatus
Next i
End If
'-----Finish Code--------
With Application
.ScreenUpdating = True
.DisplayStatusBar = True
.DisplayAlerts = True
.EnableEvents = True
End With
'------------------------
End Sub
And the function to get the worksheet from the workbook
Function GetWsFromCodeName(wb As Workbook, CodeName As String) As Excel.Worksheet
Dim ws As Excel.Worksheet
For Each ws In wb.Worksheets
If ws.CodeName = CodeName Then
Set GetWsFromCodeName = ws
Exit For
End If
Next ws
End Function
Assuming the control is on Sheet1, you should be able to use:
Sheet1.RowHightlightToggle.Caption = "Row Highlight - On"
But you can also get at the control using the shapes collection:
Sheet1.Shapes("RowHightlightToggle").DrawingObject.Object.Caption = "Row Highlight - On"
Or, with a more generic workbook variable:
Dim userWorkbook as Workbook
Set userWorkbook = Workbooks("UserData.xlsm")
userWorkbook.Worksheets("Foo").Shapes("RowHightlightToggle").DrawingObject.Object.Caption = "Row Highlight - On"

Excel Macro for Updating log

I am looking to create a macro where I take what I have in a master file that is constantly being updating on the last row and placing this into a separate log file.
I would only like to copy specific cells from the last row of the original and paste them into the log file, i've gotten close I believe but need help with the following areas:
Selection of the specific columns in the last row
How to not have the log file open or activated at any point for this to happen when the Macro is run.
I apologize if this question has been answered but I can't seem to curate all the information I am finding online to an applicable solution. Here is the macro I have thus far...
' copy2 Macro
'
Range("B5000").End(xlUp).Select
Selection.EntireRow.copy
Windows("Daily Referral Log.xlsx").Activate
Range("A65536").End(xlUp).Offset(1, 0).Select
ActiveSheet.Paste
End Sub
Looks like you're trying to open the log workbook and paste the last row from a data file into it.
I think this is what you're looking for.
Please let me know if you need something else.
How to not have the log file open or activated at any point for this to happen when the Macro is run.
Regarding this line, I think I am understanding you right.
You don't want to have to open it yourself manually; you want the code to do it.
If that's not what you mean, please let me know (you will have to lock the file for write access to modify it regardless).
Sub CopyLastRowToLog()
Dim ThisWb, wb As Workbook
Set ThisWb = ThisWorkbook
Application.EnableEvents = False
Application.DisplayAlerts = False
Application.ScreenUpdating = False
On Error Resume Next
Set wb = Workbooks.Open("FileName and Path Goes Here") 'Edit This Line
On Error GoTo 0
'Basic Error Handling - Probably worth adding ReadOnly check but keeping code short
If wb Is Nothing Then
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
MsgBox ("Error Opening File")
Exit Sub
End If
'Put the names of the sheets you're using below.
'The first 2 sheets should be the sheet you're copying from
'The second 2 sheets should be the sheet you're copying to
ThisWb.Sheets("Sheet1").Range("A" & Sheets("Sheet1").UsedRange.Rows.Count).EntireRow.Copy _
wb.Sheets("Sheet1").Range("A" & Sheets("Sheet1").UsedRange.Rows.Count + 1)
wb.Close (True)
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Edit:
To answer your first question, the file name looks weird:
Workbooks.Open("C:\Users\EYousefi\Desktop[Daily Referral Log.xlsx]Sheet1")
It should probably be:
Workbooks.Open("C:\Users\EYousefi\Desktop\Daily Referral Log.xlsx")
You don't need to specify the sheet there.
Secondly, to copy specific columns, you would want to change the copy line.
I added 2 new variables to make it easier to read:
'Get the last rows for the workbooks
Dim ThisWBLR, FinalWBLR
ThisWBLR = ThisWB.Sheets("Sheet5").UsedRange.Rows.Count
FinalWBLR = wb.Sheets("Sheet1").UsedRange.Rows.Count+1
ThisWb.Sheets("Sheet5").Range("B" & ThisWBLR & ":D" & ThisWBLR).Copy _
wb.Sheets("Sheet1").Range("B" & FinalWBLR)
You can also specify individual pieces of data one at a time if it is easier for you:
'Copy B to B
ThisWB.Sheets("Sheet5").Range("B" & ThisWBLR).Copy wb.Sheets("Sheet1").Range("B" & FinalWBLR)
'Copy C to C
ThisWB.Sheets("Sheet5").Range("C" & ThisWBLR).Copy wb.Sheets("Sheet1").Range("C" & FinalWBLR)

VBA Excel macro: use Range to act on a different worksheet

I am very much a beginner when it comes to VBA programming.
I have a Macro that hides or shows columns based on the value in one cell:
Sub HideColumnsMacro()
Range("b8:o8").EntireColumn.Hidden = False
v1 = Range("b2").Value + 1
If v1 < 12 Then
With Range("b8")
Range(.Offset(0,v1), .Offset(0, 12)).EntireColumn.Hidden = True
End With
End If
End Sub
I want to be able to get this same functionality when I change a cell on a different sheet. Is there a way I can tell this Macro to act on this sheet, when it is run from a different one?
In your macro, specify the exact sheet:
Sheets("Sheet1").Range("b8:o8").EntireColumn.Hidden = False
Qualify your Ranges with the name of the worksheet:
Sheet1.Range("b8:o8").EntireColumn.Hidden = False