2016-03-31 90 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運行干擾連接。您可能希望在創建連接時刪除連接,或者僅使用刷新方法來維護數據。