2016-03-31 53 views
1

我的子程序在单独的工作表上运行时工作正常,但是我在运行每个工作表时遇到了很多问题。子程序是一个在线CSV数据库的简单查询,但它只在第一张纸上执行25次。无法弄清楚为什么这是我的生活。Excel VBA麻烦循环遍历表和调用子程序

我能够通过这个循环做计算,但不能让它在每张纸上运行子程序。

Sub Datacollection() 

    Dim ws As Worksheet 
    For Each ws In Worksheets 

    ws.Application.Run "Gethistory" 

    Next ws 
End Sub 


Sub Gethistory() 
Dim Target As Variant 
Dim Name As Variant 
' 
Set Target = Range("B1") 
Set Name = Range("B2") 

    With ActiveSheet.QueryTables.Add(Connection:= _ 
    "Text;" & Target, _ 
    Destination:=Range("$A$3")) 
    .Name = Name 
    .FieldNames = True 
    .RowNumbers = False 
    .FillAdjacentFormulas = False 
    .PreserveFormatting = True 
    .RefreshOnFileOpen = False 
    .RefreshStyle = xlOverwriteCells 
    .SavePassword = False 
    .SaveData = True 
    .AdjustColumnWidth = True 
    .RefreshPeriod = 0 
    .TextFilePromptOnRefresh = False 
    .TextFilePlatform = 437 
    .TextFileStartRow = 1 
    .TextFileParseType = xlDelimited 
    .TextFileTextQualifier = xlTextQualifierDoubleQuote 
    .TextFileConsecutiveDelimiter = True 
    .TextFileTabDelimiter = True 
    .TextFileSemicolonDelimiter = False 
    .TextFileCommaDelimiter = True 
    .TextFileSpaceDelimiter = True 
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1) 
    .TextFileTrailingMinusNumbers = True 
    .Refresh BackgroundQuery:=False 
End With 

End Sub 

回答

2

备齐工作表中的主回路进行处理,并传递给getHistory子作为参数。

Option Explicit 

Sub dataCollection() 
    Dim w As Long 
    For w = 1 To Worksheets.Count 
     getHistory Worksheets(w) 
    Next w 
End Sub 


Sub getHistory(ws As Worksheet) 
    Dim trgt As Range, nm As Range 

    With ws 
     Set trgt = .Range("B1") 
     Set nm = .Range("B2") 

     With .QueryTables.Add(Connection:= _ 
      "Text;" & trgt.Value, _ 
      Destination:=.Range("$A$3")) 
      .Name = nm.Value 
      .FieldNames = True 
      .RowNumbers = False 
      .FillAdjacentFormulas = False 
      .PreserveFormatting = True 
      .RefreshOnFileOpen = False 
      .RefreshStyle = xlOverwriteCells 
      .SavePassword = False 
      .SaveData = True 
      .AdjustColumnWidth = True 
      .RefreshPeriod = 0 
      .TextFilePromptOnRefresh = False 
      .TextFilePlatform = 437 
      .TextFileStartRow = 1 
      .TextFileParseType = xlDelimited 
      .TextFileTextQualifier = xlTextQualifierDoubleQuote 
      .TextFileConsecutiveDelimiter = True 
      .TextFileTabDelimiter = True 
      .TextFileSemicolonDelimiter = False 
      .TextFileCommaDelimiter = True 
      .TextFileSpaceDelimiter = True 
      .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1) 
      .TextFileTrailingMinusNumbers = True 
      .Refresh BackgroundQuery:=False 
     End With 
    End With 

End Sub 

如果这样反反复复,你将最终获得了很多,可以在一般的工作簿效率以及未来getHistory运行干扰连接。您可能希望在创建连接时删除连接,或者仅使用刷新方法来维护数据。