我正在尝试编写VBA代码,这样每当我打开excel中的任何文件时,它会自动转到所有工作表中的Cell A1(无论上次保存时选择了哪些单元格)。我在网上发现了一些建议在我的Personal .xlsb项目中添加以下代码:
Sub kTest()
Dim i As Long, s() As String, a As String, n As Long
With ActiveWorkbook
For i = 1 To .Worksheets.Count
a = a & .Worksheets(i).Name
n = n + 1
ReDim Preserve s(1 To n)
s(n) = .Worksheets(i).Name
If Len(a) > 224 Then
.Worksheets(s).Select
.Worksheets(s(1)).Activate
[a1].Select
n = 0: a = "": Erase s
End If
Next
If Len(a) Then
.Worksheets(s).Select
.Worksheets(s(1)).Activate
[a1].Select
End If
Application.Goto .Worksheets(1).Range("a1")
End With
End Sub
但是当我打开文件时没有任何反应。请帮忙!
答案 0 :(得分:3)
您不能在每张纸上转到Cell A1。但是,如果您想要单张表格中的单元格A1,您可以执行以下操作。
使用以下代码创建一个ExcelEvents类
Option Explicit
Private WithEvents App As Application
Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
App.Goto Wb.Worksheets(1).Range("A1")
End Sub
Private Sub Class_Initialize()
Set App = Application
End Sub
在ThisWorkbook中添加
Option Explicit
Private xlApp As ExcelEvents
Private Sub Workbook_Open()
Set xlApp = New ExcelEvents
End Sub
保存工作簿,重新打开它,workbook_open事件中的代码将运行,这意味着只要打开另一个工作簿,代码就会转到工作表1的单元格A1
编辑如果你真的想在每张纸上选择A1,你可以按如下方式更改代码
Private Sub App_WorkbookOpen(ByVal Wb As Workbook)
Dim sh As Worksheet
App.ScreenUpdating = False
For Each sh In Wb.Worksheets
sh.Select
sh.Range("A1").Select
Next
App.Goto Wb.Worksheets(1).Range("A1")
App.ScreenUpdating = True
End Sub
答案 1 :(得分:0)
一个简单的解决方案:
For Each Sheet In ActiveWorkbook.Worksheets
Sheet.Select
Range("A1").Select
Next
答案 2 :(得分:0)
使用MicScoPau循环浏览工作表 将以下代码放在Personal.xlsb的ThisWorkbook模块中: 你必须重新打开excel才能让它第一次工作。 如果隐藏了Personal.xlsb,那么activeworkbook中的每个工作表都会出现问题。
Private WithEvents app As Application
Private Sub app_WorkbookOpen(ByVal Wb As Workbook)
For Each Sheet In ActiveWorkbook.Worksheets
Sheet.Select
Range("A1").Select
Next
End Sub
Private Sub Workbook_Open()
Set app = Application
End Sub