Worksheet 物件 (Excel)

代表工作表。

註解

Worksheet物件是Worksheets集合的成員。 Worksheets 集合包含活頁簿中的所有 Worksheet 物件。

Worksheet物件也是Sheets集合的成員。 Sheets 集合包含活頁簿中的所有工作表 (圖表與工作表都包含在內)。

範例

使用 工作表 (索引) ,其中 index 是工作表的索引編號或名稱,可傳回單一 Worksheet 物件。 下列範例會隱藏使用中活頁簿中的第一張工作表。

Worksheets(1).Visible = False

工作表索引編號表示的工作表在活頁簿索引標籤列上的位置。 Worksheets(1) 是活頁簿上第一張 (最左邊) 工作表,Worksheets(Worksheets.Count) 是最後一張。 所有工作表都會包含在索引計數中,即使它們已隱藏也一樣。

工作表名稱會顯示在工作表的索引標籤上。 使用 Name 屬性可設定或傳回工作表名稱。 下列範例會保護 Sheet1 上的分析藍本。

 
Dim strPassword As String 
strPassword = InputBox ("Enter the password for the worksheet") 
Worksheets("Sheet1").Protect password:=strPassword, scenarios:=True

當工作表是現用工作表時,您可以使用 ActiveSheet 屬性來參考它。 下列範例會使用 Activate 方法來啟用 Sheet1、將頁面方向設定為橫向模式,然後列印工作表。

Worksheets("Sheet1").Activate 
ActiveSheet.PageSetup.Orientation = xlLandscape 
ActiveSheet.PrintOut

此範例會使用 BeforeDoubleClick 事件在記事本中開啟一組指定的檔案。 若要使用此範例,您的工作表必須包含下列資料:

  • 儲存格 A1 必須包含要開啟的檔案名稱,且每個名稱均以逗號和空格分隔。
  • 儲存格 D1 必須包含記事本檔案所在位置的路徑。
  • 儲存格 D2 必須包含記事本程式所在位置的路徑。
  • 儲存格 D3 必須包含記事本檔案的副檔名且不含句點 (txt)。

當您按兩下儲存格 A1 時,於儲存格 A1 中指定的檔案會在記事本內開啟。

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
   'Define your variables.
   Dim sFile As String, sPath As String, sTxt As String, sExe As String, sSfx As String
   
   'If you did not double-click on A1, then exit the function.
   If Target.Address <> "$A$1" Then Exit Sub
   
   'If you did double-click on A1, then override the default double-click behavior with this function.
   Cancel = True
   
   'Set the path to the files, the path to Notepad, the file extension of the files, and the names of the files,
   'based on the information on the worksheet.
   sPath = Range("D1").Value
   sExe = Range("D2").Value
   sSfx = Range("D3").Value
   sFile = Range("A1").Value
   
   'Remove the spaces between the file names.
   sFile = WorksheetFunction.Substitute(sFile, " ", "")
   
   'Go through each file in the list (separated by commas) and
   'create the path, call the executable, and move on to the next comma.
   Do While InStr(sFile, ",")
      sTxt = sPath & "\" & Left(sFile, InStr(sFile, ",") - 1) & "." & sSfx
      If Dir(sTxt) <> "" Then Shell sExe & " " & sTxt, vbNormalFocus
      sFile = Right(sFile, Len(sFile) - InStr(sFile, ","))
   Loop
   
   'Finish off the last file name in the list
   sTxt = sPath & "\" & sFile & "." & sSfx
   If Dir(sTxt) <> "" Then Shell sExe & " " & sTxt, vbNormalNoFocus
End Sub

事件

方法

屬性

另請參閱

支援和意見反應

有關於 Office VBA 或這份文件的問題或意見反應嗎? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應