2012-03-09 31 views
10

Tengo el nombre de una hoja de trabajo almacenada como una cadena en una variable. ¿Cómo realizo alguna operación en esta hoja de trabajo?¿Referencia a la hoja de trabajo de Excel por nombre?

que aunque me gustaría hacer algo como esto:

nameOfWorkSheet = "test" 
ActiveWorkbook.Worksheets(nameOfWorkSheet).someOperation() 

¿Cómo hacer esto?

+0

Hmm creo que en mi frustración hice esta pregunta antes de tiempo. Encontré una solución que va más o menos así Hoja (nameOfWorkSheet) .Range ("A4") .... etc –

+2

Eso debería ser Sheets (nameOfWorkSheet) .Range ("A4"). Perdió una "S" en "Hojas" –

+1

El código que publicó funciona bien ... ¿Lo intentó antes de publicar? 'Sheets' y' Worksheets' le darán el mismo resultado. –

Respuesta

10

Existen varias opciones, incluido el uso del método que se muestra, Con y el uso de una variable.

Mi preferencia es la opción 4 a continuación: Dim y guarde la hoja de cálculo y llame a los métodos sobre la variable o páselos a las funciones, sin embargo, cualquiera de las opciones funciona.

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

Para ampliar la respuesta de Ryan, cuando se está declarando variables (mediante Dim) se puede engañar un poco mediante la función de texto predictivo en el VBE, como en la imagen de abajo. screenshot of predictive text in VBE

Si aparece en esa lista, puede asignar un objeto de ese tipo a una variable. Así que no solo una hoja de trabajo, como lo señaló Ryan, sino también una tabla, un rango, un libro de trabajo, una serie y mucho más.

Establezca esa variable igual al objeto que desea manipular y luego puede llamar a métodos, pasarlo a funciones, etc., tal como lo señaló Ryan para este ejemplo. Puede encontrarse con un par de inconvenientes cuando se trata de colecciones versus objetos (Gráfico o Gráficos, Rango o Rangos, etc.) pero con prueba y error lo obtendrá con seguridad.

4

La mejor manera es crear una variable del tipo Worksheet, asignar la hoja de trabajo y usarla cada vez que el VBA use implícitamente el ActiveSheet.

Esto lo ayudará a evitar errores que eventualmente aparecerán cuando su programa crezca de tamaño.

Por ejemplo, algo así como Range("A1:C10").Sort Key1:=Range("A2") es bueno cuando la macro solo funciona en una hoja. Pero eventualmente expandirá su macro para que funcione con varias hojas, descubra que esto no funciona, ajústelo al ShTest1.Range("A1:C10").Sort Key1:=Range("A2") ... y descubra que todavía no funciona.

Aquí es la forma correcta:

Dim ShTest1 As Worksheet 
Set ShTest1 = Sheets("Test1") 
ShTest1.Range("A1:C10").Sort Key1:=ShTest1.Range("A2") 
Cuestiones relacionadas