如何在VBA中提取工作表名称?

时间:2017-09-20 15:58:36

标签: excel vba extract

我有一个脚本可以从多个excel工作簿中的某个选项卡中为我提取一些数据。

我想知道如何添加它以提取它经历的每个工作簿的工作簿名称

这就是我正在使用的:

Dim fPath As String
Dim iSheet As String
Dim oSheet As String
Dim BMsheet As String

Dim country, bas, play As String
Dim fileNames As Range
Dim file As Range
Dim oWorkbook As Excel.Workbook ' outlook workbook

Dim MyRange As Range

iSheet = "INPUT"
oSheet = "Data"
BMsheet = "Potential Discovery Phasing"

Dim fHandle As New FileSystemObject

ThisWorkbook.Worksheets(iSheet).Activate
Set fileNames = Range("files")
ThisWorkbook.Worksheets(oSheet).Activate
Range("start").Activate

On Error GoTo NotFound:

For Each file In fileNames.Cells
    If fHandle.FileExists(file.Value) Then
        Set oWorkbook = Workbooks.Open(file.Value, False, True)
        'extract columns

        ''''''''''''''''''''''''''''''''''''''''''''''''
        '
        ''''''''''''''''''''''''''''''''''''''''''''''''
        oWorkbook.Worksheets(BMsheet).Select

        If ActiveSheet.AutoFilterMode = True Then ActiveSheet.AutoFilterMode = False

        Range("A6").Select

        ActiveCell.Offset(1, 0).Select
        Set MyRange = Range(ActiveCell, ActiveCell.Offset(32, 7))

        MyRange.Select

        Range(Selection, Selection.End(xlDown)).Select
        Selection.Copy

        ThisWorkbook.Activate
        ThisWorkbook.Worksheets(oSheet).Select
        Selection.PasteSpecial xlValues

       'While ActiveCell.Value <> ""
             'ActiveCell.Offset(0, -1).Value = file.Offset(0, -2).Value
             ActiveCell.Offset(33, 0).Activate
       'Wend

        Application.CutCopyMode = False
        oWorkbook.Close SaveChanges:=False

        ActiveCell.Select
        file.Offset(0, 1).Value = "Yes"
    Else
        file.Offset(0, 1).Value = "No"
    End If

Skip: Next file

    Exit Sub

NotFound:
    GoTo Skip
End Sub

我对VBA相当新,所以请原谅我缺乏知识

干杯

1 个答案:

答案 0 :(得分:1)

dim sheet as worksheet
dim wb as workbook
set wb = thisworkbook

for each sheet in wb.Sheets
    debug.print; sheet.Name
next sheet

因为我们是书呆子,想要检查一下:

Private Sub this()
    For i = 0 To 99
        Debug.Print i;
        'prints to the same line
    Next i

    For i = 0 To 99
        Debug.Print ; i
        prints to next line
    Next i
End Sub