我想使用VBA代码

时间:2018-04-09 12:36:03

标签: excel-vba vba excel

下面的查询单行成功运行,我想重复一遍,直到' A'行是空的。基本上,我从A2复制并执行它,结果将被加载到B2中。然后创建一个文本文件存储'查询n结果'并创建一个超链接。

请帮我创建一个循环并执行此操作直到' A'列是空的

这是我的查询:

'First Query
Set Sql = Sheet1.Range("A2")
Set Rec_set = cn.Execute(Sql) 'Issue SQL statement
While Not Rec_set.EOF
Sheet1.Range("B2").CopyFromRecordset Rec_set
Wend
Rec_set.Close 'Close the recordset

'Write into TEXT file
Set Fileout = fso.CreateTextFile("C:\Text\Row2.txt", True, True)
Fileout.Write Sheet1.Range("A2")
Fileout.Write vbNewLine
Fileout.Write vbNewLine
Fileout.Write "COUNT"
Fileout.Write vbNewLine
Fileout.Write "*****"
Fileout.Write vbNewLine
Fileout.Write Sheet1.Range("B2")
Fileout.Close
With Worksheets("Sheet1")
    .Hyperlinks.Add Anchor:=.Range("C2").End(xlUp).Offset(1, 0), _
        Address:="https:XXXXXXXXXXXXX/Screenshots/Text/Row2.txt", _
        ScreenTip:="Hyperlink", _
        TextToDisplay:="Row2"
End With

谢谢,

2 个答案:

答案 0 :(得分:0)

您需要从A的第一行到A的最后一行的循环。因此,在空工作表上,在A列中写下几个单词并分别尝试此部分。然后将其调整为您的代码:

Option Explicit

Public Sub TestMe()

    Dim lastRowA As Long
    Dim cnt As Long

    lastRowA = lastRow

    For cnt = 1 To lastRowA
        Debug.Print Cells(cnt, 1)
    Next cnt

End Sub

Function lastRow(Optional wsName As String, Optional columnToCheck As Long = 1) As Long

    Dim ws As Worksheet

    If wsName = vbNullString Then
        Set ws = ActiveSheet
    Else
        Set ws = Worksheets(wsName)
    End If

    lastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row

End Function

lastRow函数有2个可选参数 - 因此,如果您需要B的{​​{1}}列的最后一行,那么它看起来像这样 - > Sheets2

答案 1 :(得分:0)

我相信以下内容应该按预期工作:

Sub foo()
LastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row
'First Query
For i = 2 To LastRow
    Set Sql = Sheet1.Range("A" & i)
    Set Rec_set = cn.Execute(Sql) 'Issue SQL statement
    While Not Rec_set.EOF
    Sheet1.Range("B" & i).CopyFromRecordset Rec_set
    Wend
    Rec_set.Close 'Close the recordset

    NewPath = "C:\Text\Row" & i & ".txt"
    'Write into TEXT file
    Set Fileout = fso.CreateTextFile(NewPath, True, True)
    Fileout.Write Sheet1.Range("A" & i)
    Fileout.Write vbNewLine
    Fileout.Write vbNewLine
    Fileout.Write "COUNT"
    Fileout.Write vbNewLine
    Fileout.Write "*****"
    Fileout.Write vbNewLine
    Fileout.Write Sheet1.Range("B" & i)
    Fileout.Close
    With Worksheets("Sheet1")
        .Hyperlinks.Add Anchor:=.Range("C" & i).End(xlUp).Offset(1, 0), _
            Address:="https:XXXXXXXXXXXXXXXXXXXXXX/Screenshots/Text/Row" & i & ".txt", _
            ScreenTip:="Hyperlink", _
            TextToDisplay:="Row" & i
    End With
Next i
End Sub