MyTetra Share
Делитесь знаниями!
Объект листа (Excel)
Время создания: 12.10.2019 20:30
Раздел: !Закладки - VBA - Excel - Листы
Запись: xintrea/mytetra_db_adgaver_new/master/base/1570884755dir2tvkjag/text.html на raw.githubusercontent.com

Объект листа (Excel)Worksheet object (Excel)

  • ‎15‎.‎05‎.‎2019
  • Время чтения: 2 мин


В этой статье

  1. Примечания
  2. Пример
  3. События
  4. Методы
  5. Свойства
  6. См. также

Представляет лист.Represents a worksheet.

ПримечанияRemarks

Объект листа является элементом коллекции листы .The Worksheet object is a member of the Worksheets collection. Коллекция листы содержит все объекты листа в книге.The Worksheets collection contains all the Worksheet objects in a workbook.

Объект листа также является членом коллекции Sheets .The Worksheet object is also a member of the Sheets collection. Коллекция Sheets содержит все листы в книге (листы и листы диаграммы).The Sheets collection contains all the sheets in the workbook (both chart sheets and worksheets).

ПримерExample

Используйте листы (индекс), где индекс — это номер или имя индекса листа, чтобы вернуть один объект листа .Use Worksheets (index), where index is the worksheet index number or name, to return a single Worksheet object. В приведенном ниже примере показано, как скрыть лист один в активной книге.The following example hides worksheet one in the active workbook.

VB Копировать

Worksheets(1).Visible = False


Номер индекса листа указывает положение листа на панели вкладок книги.The worksheet index number denotes the position of the worksheet on the workbook's tab bar. Worksheets(1)— Это первый (крайний левый) лист в книге, Worksheets(Worksheets.Count) который является последним.Worksheets(1) is the first (leftmost) worksheet in the workbook, and Worksheets(Worksheets.Count) is the last one. Все листы включены в число индексов, даже если они скрыты.All worksheets are included in the index count, even if they are hidden.


Имя листа отображается на вкладке листа.The worksheet name is shown on the tab for the worksheet. Используйте свойство Name , чтобы задать или вернуть имя листа.Use the Name property to set or return the worksheet name. В приведенном ниже примере показано, как защитить сценарии на листе Sheet1.The following example protects the scenarios on Sheet1.

VB Копировать

Dim strPassword As String

strPassword = InputBox ("Enter the password for the worksheet")

Worksheets("Sheet1").Protect password:=strPassword, scenarios:=True



Когда лист является активным листом, можно использовать свойство активешит , чтобы ссылаться на него.When a worksheet is the active sheet, you can use the ActiveSheet property to refer to it. В следующем примере используется метод Activate для активации Лист1, устанавливается альбомная ориентация страницы, а затем лист печатается.The following example uses the Activate method to activate Sheet1, sets the page orientation to landscape mode, and then prints the worksheet.

VB Копировать

Worksheets("Sheet1").Activate

ActiveSheet.PageSetup.Orientation = xlLandscape

ActiveSheet.PrintOut



В этом примере показано использование события бефоредаублекликк для открытия указанного набора файлов в блокноте.This example uses the BeforeDoubleClick event to open a specified set of files in Notepad. Чтобы использовать этот пример, лист должен содержать следующие данные:To use this example, your worksheet must contain the following data:

  • Ячейка a1 должна содержать имена файлов, которые должны быть открыты, отделенных запятой и пробелом.Cell A1 must contain the names of the files to open, each separated by a comma and a space.
  • Ячейка D1 должна содержать путь к расположению файлов блокнота.Cell D1 must contain the path to where the Notepad files are located.
  • Ячейка D2 должна содержать путь к расположению программы блокнота.Cell D2 must contain the path to where the Notepad program is located.
  • Ячейка D3 должна содержать расширение файла (без точки) для файлов "Блокнота" (txt).Cell D3 must contain the file extension, without the period, for the Notepad files (txt).

При двойном щелчке ячейки a1 файлы, указанные в ячейке a1, открываются в блокноте.When you double-click cell A1, the files specified in cell A1 are opened in Notepad.

VB Копировать

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


СобытияEvents

  • ActivateActivate
  • BeforeDeleteBeforeDelete
  • BeforeDoubleClickBeforeDoubleClick
  • BeforeRightClickBeforeRightClick
  • CalculateCalculate
  • ChangeChange
  • DeactivateDeactivate
  • FollowHyperlinkFollowHyperlink
  • LensGalleryRenderCompleteLensGalleryRenderComplete
  • PivotTableAfterValueChangePivotTableAfterValueChange
  • PivotTableBeforeAllocateChangesPivotTableBeforeAllocateChanges
  • PivotTableBeforeCommitChangesPivotTableBeforeCommitChanges
  • PivotTableBeforeDiscardChangesPivotTableBeforeDiscardChanges
  • PivotTableChangeSyncPivotTableChangeSync
  • PivotTableUpdatePivotTableUpdate
  • SelectionChangeSelectionChange
  • TableUpdateTableUpdate

МетодыMethods

  • ActivateActivate
  • CalculateCalculate
  • ChartObjectsChartObjects
  • CheckSpellingCheckSpelling
  • CircleInvalidCircleInvalid
  • ClearArrowsClearArrows
  • ClearCirclesClearCircles
  • CopyCopy
  • DeleteDelete
  • EvaluateEvaluate
  • ExportAsFixedFormatExportAsFixedFormat
  • MoveMove
  • OLEObjectsOLEObjects
  • PastePaste
  • PasteSpecialPasteSpecial
  • PivotTablesPivotTables
  • PivotTableWizardPivotTableWizard
  • PrintOutPrintOut
  • PrintPreviewPrintPreview
  • ProtectProtect
  • ResetAllPageBreaksResetAllPageBreaks
  • SaveAsSaveAs
  • ScenariosScenarios
  • SelectSelect
  • SetBackgroundPictureSetBackgroundPicture
  • ShowAllDataShowAllData
  • ShowDataFormShowDataForm
  • UnprotectUnprotect
  • XmlDataQueryXmlDataQuery
  • XmlMapQueryXmlMapQuery

СвойстваProperties

  • ApplicationApplication
  • AutoFilterAutoFilter
  • AutoFilterModeAutoFilterMode
  • CellsCells
  • CircularReferenceCircularReference
  • CodeNameCodeName
  • ColumnsColumns
  • CommentsComments
  • КомментссреадедCommentsThreaded
  • ConsolidationFunctionConsolidationFunction
  • ConsolidationOptionsConsolidationOptions
  • ConsolidationSourcesConsolidationSources
  • CreatorCreator
  • CustomPropertiesCustomProperties
  • DisplayPageBreaksDisplayPageBreaks
  • DisplayRightToLeftDisplayRightToLeft
  • EnableAutoFilterEnableAutoFilter
  • EnableCalculationEnableCalculation
  • EnableFormatConditionsCalculationEnableFormatConditionsCalculation
  • EnableOutliningEnableOutlining
  • EnablePivotTableEnablePivotTable
  • EnableSelectionEnableSelection
  • FilterModeFilterMode
  • HPageBreaksHPageBreaks
  • HyperlinksHyperlinks
  • IndexIndex
  • ListObjectsListObjects
  • MailEnvelopeMailEnvelope
  • NameName
  • NamesNames
  • NextNext
  • OutlineOutline
  • PageSetupPageSetup
  • ParentParent
  • PreviousPrevious
  • PrintedCommentPagesPrintedCommentPages
  • ProtectContentsProtectContents
  • ProtectDrawingObjectsProtectDrawingObjects
  • ProtectionProtection
  • ProtectionModeProtectionMode
  • ProtectScenariosProtectScenarios
  • QueryTablesQueryTables
  • RangeRange
  • RowsRows
  • ScrollAreaScrollArea
  • ShapesShapes
  • SortSort
  • StandardHeightStandardHeight
  • StandardWidthStandardWidth
  • TabTab
  • TransitionExpEvalTransitionExpEval
  • TransitionFormEntryTransitionFormEntry
  • TypeType
  • UsedRangeUsedRange
  • VisibleVisible
  • VPageBreaksVPageBreaks

См. такжеSee also

  • Справочник по объектной модели ExcelExcel Object Model Reference

Поддержка и обратная связьSupport and feedback

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи?Have questions or feedback about Office VBA or this documentation? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь .

Так же в этом разделе:
 
MyTetra Share v.0.59
Яндекс индекс цитирования