我将工作表的名称存储为变量中的字符串。如何在此工作表上执行某些操作?
我虽然会做这样的事情:
nameOfWorkSheet = "test"
ActiveWorkbook.Worksheets(nameOfWorkSheet).someOperation()
我该如何完成这项工作?
答案 0 :(得分:12)
有几个选项,包括使用您演示的方法,使用和使用变量。
我的偏好是下面的选项4:Dim
类型Worksheet
的变量并存储工作表并调用变量上的方法或将其传递给函数,但是任何选项都可以。
Sub Test()
Dim SheetName As String
Dim SearchText As String
Dim FoundRange As Range
SheetName = "test"
SearchText = "abc"
' 0. If you know the sheet is the ActiveSheet, you can use if directly.
Set FoundRange = ActiveSheet.UsedRange.Find(What:=SearchText)
' Since I usually have a lot of Subs/Functions, I don't use this method often.
' If I do, I store it in a variable to make it easy to change in the future or
' to pass to functions, e.g.: Set MySheet = ActiveSheet
' If your methods need to work with multiple worksheets at the same time, using
' ActiveSheet probably isn't a good idea and you should just specify the sheets.
' 1. Using Sheets or Worksheets (Least efficient if repeating or calling multiple times)
Set FoundRange = Sheets(SheetName).UsedRange.Find(What:=SearchText)
Set FoundRange = Worksheets(SheetName).UsedRange.Find(What:=SearchText)
' 2. Using Named Sheet, i.e. Sheet1 (if Worksheet is named "Sheet1"). The
' sheet names use the title/name of the worksheet, however the name must
' be a valid VBA identifier (no spaces or special characters. Use the Object
' Browser to find the sheet names if it isn't obvious. (More efficient than #1)
Set FoundRange = Sheet1.UsedRange.Find(What:=SearchText)
' 3. Using "With" (more efficient than #1)
With Sheets(SheetName)
Set FoundRange = .UsedRange.Find(What:=SearchText)
End With
' or possibly...
With Sheets(SheetName).UsedRange
Set FoundRange = .Find(What:=SearchText)
End With
' 4. Using Worksheet variable (more efficient than 1)
Dim MySheet As Worksheet
Set MySheet = Worksheets(SheetName)
Set FoundRange = MySheet.UsedRange.Find(What:=SearchText)
' Calling a Function/Sub
Test2 Sheets(SheetName) ' Option 1
Test2 Sheet1 ' Option 2
Test2 MySheet ' Option 4
End Sub
Sub Test2(TestSheet As Worksheet)
Dim RowIndex As Long
For RowIndex = 1 To TestSheet.UsedRange.Rows.Count
If TestSheet.Cells(RowIndex, 1).Value = "SomeValue" Then
' Do something
End If
Next RowIndex
End Sub
答案 1 :(得分:6)
最好的方法是创建一个Worksheet
类型的变量,分配工作表并在每次VBA隐式使用ActiveSheet
时使用它。
这将有助于您避免在程序规模扩大时最终出现的错误。
例如,当宏仅在一张纸上工作时,像Range("A1:C10").Sort Key1:=Range("A2")
这样的东西是好的。但是你最终会扩展你的宏以使用几张表,发现这不起作用,将其调整为ShTest1.Range("A1:C10").Sort Key1:=Range("A2")
...并发现它仍然无法正常工作。
这是正确的方法:
Dim ShTest1 As Worksheet
Set ShTest1 = Sheets("Test1")
ShTest1.Range("A1:C10").Sort Key1:=ShTest1.Range("A2")
答案 2 :(得分:2)
要扩展Ryan的答案,当您声明变量(使用Dim)时,您可以使用VBE中的预测文本功能作弊,如下图所示。
如果它出现在该列表中,则可以将该类型的对象分配给变量。所以不仅仅是Ryan指出的工作表,还有图表,范围,工作簿,系列等等。
您将该变量设置为您想要操作的对象,然后您可以调用方法,将其传递给函数等,就像Ryan为此示例所指出的那样。当涉及集合与对象(图表或图表,范围或范围等)时,您可能遇到一些障碍,但是通过试验和错误,您肯定会得到它。