Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA Use selected sheet

Tags:

excel

vba

Excel VBA newbie here. I just need a macro that will refresh the queries I have on a single sheet I'm viewing. I already have the refresh macro but I always have to specify the sheet name that I want to refresh. Is it possible to have the macro run on whatever sheet I'm viewing? Here's the macro in it's current state:

Sub Refresh_Query()
Sheets("Sheet1").Select
Range("B6").Select
Selection.QueryTable.Refresh BackgroundQuery:=False
End Sub
like image 395
user1985112 Avatar asked Jan 16 '13 20:01

user1985112


People also ask

How do I select a specific worksheet in Excel?

Click the tab for the first sheet, then hold down SHIFT while you click the tab for the last sheet that you want to select. By keyboard: First, press F6 to activate the sheet tabs. Next, use the left or right arrow keys to select the sheet you want, then you can use Ctrl+Space to select that sheet.

How do I assign a macro to a specific worksheet?

Right-click the control, and then click Assign Macro. The Assign Macros dialog box appears. To specify the location of an existing macro, select where the macro is located in the Macros in box by doing one of the following: To search for the macro in any workbook that is open, select All Open Workbooks.


2 Answers

You want to use ActiveSheet.Name, such as:

Sub Refresh_Query()
    Sheets(ActiveSheet.Name).Select
    Range("B6").Select
    Selection.QueryTable.Refresh BackgroundQuery:=False
End Sub
like image 62
LittleBobbyTables - Au Revoir Avatar answered Oct 19 '22 06:10

LittleBobbyTables - Au Revoir


This should work:

Sub Refresh_Query()
    ActiveSheet.QueryTables(1).Refresh BackgroundQuery:=False
End Sub
like image 20
chuff Avatar answered Oct 19 '22 06:10

chuff