循环通过工作簿并获取值(如果存在于单元格中)

时间:2018-01-16 13:49:15

标签: excel vba excel-vba

我是VBA / Macros的新手,并设法将Worksheet名称输入我的ActiveWorkbook。我现在正在尝试检查Value中是否存在特定Cell,然后将其放在我已提取的Worksheet名称旁边的B列中。只有特定工作表的值为1-54,因为它是IED设备的地址,而且只是我关心的工作表。

目前我正在使用此代码提取Worksheet名称,因此我可以继续使用此引用来提取一系列信息,因为我无法获取工作表编号或工作表代码名称参考正确。

 Sub GetSheetnames()
 'Turn off alerts
      Application.DisplayAlerts = False

  'Open the Workbook that i want to look for the worksheet names this 
  'white book template is a save as copy of another file as it makes it 
  'easier to reference as I work with 1000's of file with same format but 
   'are all saved as a different name

  Workbooks.Open Filename:="D:\Projects\ASE Templates\ASE Template White 
  Book.xlsx"
  Dim ws As Worksheet
  Dim i As Integer
  With ThisWorkbook.Worksheets("Tab Names from white book")
  .Range("A:A").ClearContents
  For Each ws In ActiveWorkbook.Worksheets
  i = i + 1
 .Range("A" & i) = ws.Name

 Next ws

End With

 Workbooks("ASE Template White Book.xlsx").Close

  Application.DisplayAlerts = True

 End Sub

我还要添加的是检查每个H4上的Worksheet中的值是否存在,如果是,则显示提取的工作表旁边的B列中的值我的工作表A列中的名称" Tab Bookss From White book"

我确实看过重新运行宏来改变

With ThisWorkbook.Worksheets("Tab Names from white book")
   .Range("A:A").ClearContents
   For Each ws In ActiveWorkbook.Worksheets
       i = i + 1
      .Range("A" & i) = ws.Name
   Next ws

With ThisWorkbook.Worksheets("Tab Names from white book")
    .Range("B:B").ClearContents
    For Each ws In ActiveWorkbook.Worksheets
       i = i + 1
       .Range("B" & i) = H4.value

或者

.Range("B" & i) = Cells(3,8).Value

这样可以运行,但不会做任何可见的事情。任何帮助,将不胜感激。理想情况下,我想运行一次宏并同时填写两列

1 个答案:

答案 0 :(得分:0)

在我看来,好像你没有限定你想要获取的单元格区域,并且建议Set使用工作簿以便以后参考。

Sub GetSheetnames()
'Turn off alerts
Application.DisplayAlerts = False

'Open the Workbook that i want to look for the worksheet names this
'white book template is a save as copy of another file as it makes it
'easier to reference as I work with 1000's of file with same format but
'are all saved as a different name

Dim wb As Workbook
Set wb = Workbooks.Open("D:\Projects\ASE Templates\ASE Template White Book.xlsx")

Dim ws As Worksheet
Dim i As Integer
With ThisWorkbook.Worksheets("Tab Names from white book")
    .Range("A:A").ClearContents
    For Each ws In wb.Worksheets
        i = i + 1
        .Range("A" & i) = ws.Name
        .Range("B" & i) = ws.Cells(3, 8).Value
    Next ws
End With

wb.Close

Application.DisplayAlerts = True

End Sub