简体   繁体   English

打开一个Excel文件并激活工作表1以运行宏

[英]Open a Excel file and Activate sheet 1 to run macros

I need to write a VBA code that allows the user to browse and select an Excel file of his choice from a directory and then activate Sheet1 in that Excel file. 我需要编写一个VBA代码,该代码允许用户浏览并从目录中选择所需的Excel文件,然后在该Excel文件中激活Sheet1。 After that I want macros to run on the activated sheet. 之后,我希望宏在激活的工作表上运行。

please help from below forward: 请从下面向前提供帮助:

Sub GetFile()
Dim fNameAndPath As Variant, wb As Workbook
Dim sht As Worksheet

fNameAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.XLSX), *.XLSX", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Set wb = Workbooks.Open(fNameAndPath)

From here how to activate the open file, and how to activate Sheet 1 of the open file to run macros? 从这里如何激活打开的文件,以及如何激活打开文件的工作表1以运行宏?

There is no need to Activate "Sheet1" in order to run Macros on it. 无需Activate “ Sheet1”即可在其上运行宏。

If you must Activate it, use : 如果必须Activate它,请使用:

Set wb = Workbooks.Open(fNameAndPath)

' Option 1: set the first sheet (index)
Set Sht = wb.Worksheets(1) 
' Option 2: set the sheet named "Sheet1"
Set Sht = wb.Worksheets("Sheet1")    

Sht.Activate ' <-- Not sure why you would need to Activate it ?

The code will open the workbook and will assign the opened workbook to wb object. 该代码将打开工作簿,并将打开的工作簿分配给wb对象。 Automatically wb will be the active one, so there is no need to write a code for that. 自动wb将是活动的,因此无需为此编写代码。 Just to make sure Sheet1 will be activated, you should add: 为了确保Sheet1将被激活,您应该添加:

wb.sheets("Sheet1").activate

I did not quite get what you meant by "I want macros to run on the activated sheet." 我没有完全理解“我希望宏在激活的工作表上运行”的含义。 because it depends on the macro that is run. 因为它取决于运行的宏。 To make sure that the macro will use the active sheet to make changes etc you should use the object activesheet for example you can do this: 为了确保宏将使用活动工作表进行修改等你应该使用对象activesheet例如,你可以这样做:

Dim ws as worksheet
set ws=activesheet
' ...
' do whatever you want on ws in here
' ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM