[英]How to loop through rows, save these as variables and use them as variables VBA
我試圖將值作為變量存儲在工作表中,然后繼續使用該變量引用工作表並使用它進行過濾。
這將循環執行,直到程序到達第一個空單元格為止。
到目前為止,我相關的代碼是:
Sub Program()
Dim i As Integer
i = 2
Do Until IsEmpty(Cells(i, 1))
Debug.Print i
Sheets("Button").Activate
Dim First As String
First = Cells(i, 1).Value
Debug.Print First
Dim Second As String
Second = Cells(i, 2).Value
Debug.Print Second
'Filters my Data sheet and copies the data
Sheets("DATA").Activate
Sheets("DATA").Range("A1").AutoFilter _
Field:=2, _
Criteria1:=First 'Filters for relevant organisation
Sheets("DATA").Range("A1").AutoFilter _
Field:=6, _
Criteria1:="=" 'Filters for No Response
Sheets("DATA").Range("A1:H6040").Copy
'This should loop through for each separate group
Sheets(CStr(Second)).Select
Range("A1").Select
ActiveSheet.Paste
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
i = i + 1
Loop
Worksheets("DATA").AutoFilterMode = False
End Sub
我已對程序進行了重大更改,試圖添加諸如“ CStr”之類的符號,因為此行出現了錯誤: Sheets(CStr(Second)).Select
它曾經用來表示Sheets(Second)).Select
和debug.print來查看它是否確實在工作,但是沒有記錄到立即窗口中。
另外,當我實際運行它時,沒有出現錯誤,但似乎沒有任何反應。
不知道要添加什么,還是要嘗試什么。 干杯!
首先,在循環內使用(至少是第一次)工作表激活似乎是不必要的,因為循環的開始是確定要使用哪個工作表來控制循環流程的因素。
此外,我認為最好完全刪除工作表激活,例如:關於.Select
的討論(情況不盡相同,但本文討論的解決方案在幾乎所有情況下都適用於.Select
和.Activate
。 ): 如何避免在Excel VBA宏中使用“選擇” 。
我們還要看看是否可以以更直接的方式引用“ DATA”表中的表以及進行一些錯誤檢查。
我的建議:
Sub Program()
Dim i As Integer
Dim First, Second As String
Dim secondWs As Worksheet
Dim dataTbl As ListObject
i = 2
Set dataTbl = Worksheets("DATA").Range("A1").ListObject.Name
' The above can be done more elegantly if you supply the name of the table
Sheets("DATA").Activate
Do Until IsEmpty(Cells(i, 1))
Debug.Print i
First = Sheets("Button").Cells(i, 1).Value
Debug.Print First
Second = Sheets("Button").Cells(i, 2).Value
Debug.Print Second
'Filters my Data sheet and copies the data
dataTbl.AutoFilter _
Field:=2, _
Criteria1:=First 'Filters for relevant organisation
dataTbl.AutoFilter _
Field:=6, _
Criteria1:="=" 'Filters for No Response
Sheets("DATA").Range("A1:H6040").Copy
'This should loop through for each separate group
On Error Resume Next
Set secondWs = Worksheets(Second)
On Error GoTo 0
If Not secondWs Is Nothing Then
secondWs.Range("A1").PasteSpecial Paste:=xlPasteValues
Else
Debug.Print "Sheet name SECOND was not found"
End If
i = i + 1
Loop
Worksheets("DATA").AutoFilterMode = False
End Sub
如果遇到任何錯誤,請說明該錯誤出現在哪一行以及錯誤消息的實際含義。
參考: http : //www.mrexcel.com/forum/excel-questions/3228-visual-basic-applications-check-if-worksheet-exists.html#post13739
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.