VBA循环通过字符串

时间:2017-03-20 14:02:20

标签: excel vba excel-vba loops

我必须遍历大量变量来过滤数据集的内容以将其粘贴到其他工作表。我必须粘贴数据的代码如下

void Initialize_Window(void)
{
    RECT rConsole;
    GetWindowRect(GetConsoleWindow(), &rConsole);
    SetWindowPos(GetConsoleWindow(), NULL, 0, 0, 800, 700, 0);
    SetWindowLong(GetConsoleWindow(), GWL_STYLE, GetWindowLong(GetConsoleWindow(), GWL_STYLE) & ~(WS_SIZEBOX | WS_MAXIMIZEBOX));
    SetWindowPos(GetConsoleWindow(), NULL, (GetSystemMetrics(SM_CXSCREEN) - rConsole.right - rConsole.left) / 2, (GetSystemMetrics(SM_CYSCREEN) - rConsole.bottom - rConsole.top) / 2, 0, 0, SWP_NOSIZE);
}

源始终相同,但是" SelectionABC"和#34; DestinationX"将改变。选择和爆炸是成对的,所以" SelectionABC"转到工作表" Destination1"," SelectionDEF"转到工作表" Destination2",...

如何循环选择&目的地,以便我不为每次数据传输重复代码?

1 个答案:

答案 0 :(得分:0)

这是一个快速未经测试的代码,可帮助您开始使用。

Dim i, j As Long
Dim alpha As String
Dim b As Boolean : b = False
j = 1

'~~> UPPERCASE ALPHABETIC CHARACTERS IN THE
'~~> ASCII TABLE GO FROM 65="A" TO 91="Z"
For i = 65 To 91
    If i = 89 Then  '~~> BECAUSE WE ARE LEFT WITH LAST TWO LETTERS "YZ"
        alpha = Chr(i) & Chr(i + 1)
        b = True    '~~> TO COME OUT OF LOOP AFTER "YZ"
    Else
        alpha = Chr(i) & Chr(i + 1) & Chr(i + 2)
        i = i + 2
    End If

    Sheets("Source").Select
    LastRow = ActiveSheet.Range("A1").Offset(ActiveSheet.Rows.Count - 1, 0).End(xlUp).Row
    If ActiveSheet.AutoFilterMode = False Then ActiveSheet.AutoFilterMode = True 'Enable Filters if not exists
    ActiveSheet.Range("$A$3:$AY$" & LastRow).AutoFilter Field:=4, Criteria1:= _
        "Selection" & alpha             '~~> ADDED alpha here
    Range("A3:AY" & LastRow).Copy
    Sheets("Destination" & j).Select    '~~> ADDED j HERE
    Range("A4").Select
    ActiveSheet.Paste

    j = j + 1
    If b Then Exit For '~~> TO COME OUT OF LOOP AFTER "YZ"
Next