简体   繁体   English

尝试并无法通过VBA在Excel中的列中循环。 我究竟做错了什么?

[英]Trying and failing to loop through a column in Excel with VBA. What am I doing wrong?

I'm trying to loop through the A column in Excel. 我试图遍历Excel中的A列。 Check if its got a value, if it has, move to the adjacent cell in the b column and check that value and store it to use for a search. 检查它是否有值(如果有),移至b列中的相邻单元格并检查该值并将其存储以用于搜索。

I can't even get the loop through the A column working yet. 我什至无法通过A列开始循环。 I've looked at hundreds of examples and what I have should work. 我看过数百个示例,我应该使用的示例。

Can someone please point out what is missing? 有人可以指出缺少的东西吗? This is my code: 这是我的代码:

Sub AdjacentRow()

    Dim xlWrkBk As Excel.Workbook

    Dim xlsht As Excel.Worksheet
    Dim xl As Excel.Application

    Set xl = CreateObject("Excel.Application")
    Set xlWrkBk = GetObject("C:\Users\my_username\Desktop\AgileProjects\ITAG Open Interactions.xlsx")
    Set xlsht = xlWrkBk.Worksheets(1)

    Dim i, j, FirstCell, LastCell As Integer
    Dim strIMresult As String


    Dim Cell, Row, Column As Excel.Range

    'Set Cell = Range("A9").End(xlDown)
    'Set Cell = Range([a1], [a250])

    For Each Row In Range("A9:A250").Rows
        If Not IsEmpty(ActiveCell.Value) Then
            'move to adjacent cell
            ActiveCell.Offset(0, 1).Select
            If Not IsEmpty(ActiveCell.Value) Then
                'copy the value
                strIMresult = ActiveCell.Value
                'ActiveCell.Offset(1, 0).Select
                'ActiveCell = strIMresult
                Debug.Print strIMresult
            Else
                ActiveCell.Offset(0, -1).Select
            End If
        End If
    Next Row

End Sub

Many of your variables are not dimensioned properly which may be contributing to errors (or may in the future contribute errors). 您的许多变量的尺寸设计不正确,可能会导致错误(或将来可能会导致错误)。

For example, Dim i, j, FirstCell, LastCell As Integer declares i , j , and FirstCell as Variant. 例如, Dim i, j, FirstCell, LastCell As Integer声明ijFirstCell为Variant。 Only LastCell as Integer . LastCell as Integer Same with: Dim Cell, Row, Column As Excel.Range which declares Cell , Row as Variant, with only Column declared as a Range variable. 与Excel相同: Dim Cell, Row, Column As Excel.RangeCellRow声明为Variant,仅将Column声明为Range变量。

This should get you started. 这应该可以帮助您入门。 I cleaned up the declarations, and I have removed the lines that you commented out and made some changes so your Loop should work properly now. 我清理了声明,并删除了您注释掉的行并进行了一些更改,以便您的Loop现在可以正常工作。

Sub AdjacentRow()

Dim xlWrkBk As Excel.Workbook

Dim xlsht As Excel.Worksheet
Dim xl As Excel.Application

Dim i#, j#, FirstCell#, LastCell#
Dim strIMresult As String
Dim cl As Excel.Range
Dim clNext As Excel.Range


Set xl = CreateObject("Excel.Application")
Set xlWrkBk = GetObject("C:\Users\my_username\Desktop\AgileProjects\ITAG Open Interactions.xlsx")
Set xlsht = xlWrkBk.Worksheets(1)

For Each cl In xlsht.Range("A9:A250")
    Set clNext = cl.Offset(0, 1)
    If Not cl.Value = vbNullString Then
        'check the adjacent cell'
        If Not clNext.Value = vbNullString Then
            'store the value'
            strIMresult = clNext.Value
            Debug.Print strIMresult
        End If
    End If
Next Row

End Sub

GENERAL COMMENT 1 一般评论1

Dimensioning in VBA should be done per variable, only the last one in a row will get the type that you specify. VBA中的尺寸应按变量进行,只有行中的最后一个将获得您指定的类型。 So the following: 因此,以下内容:

Dim Cell, Row, Column As Excel.Range

Should becomes: 应该变成:

Dim Cell As Excel.Range, Row As Excel.Range, Column As Excel.Range

If this script is in Excel VBA you dont even need to use Excel., just dimension it as Range: 如果此脚本在Excel VBA中,您甚至不需要使用Excel。,只需将其标注为Range:

Dim aa As Range

GENERAL COMMENT 2 一般评论2

You use Row, Column and Cell as local variables, these are existing Objects in Excel and should not be used as local variable names as well!! 您将Row,Column和Cell用作局部变量,它们是Excel中的现有对象,因此也不应用作局部变量名称!! Furthermore they are not saying much with names like this. 此外,他们对这样的名字并没有多说。 Please changes those variable/object names to something meaningful AND unique! 请将这些变量/对象名称更改为有意义且唯一的名称!

Now to the problem 现在解决问题

You do loop through the Rows, however your script doesnt interact with the Row at all! 您确实遍历了行,但是您的脚本根本不与行交互! Your script is interacting with the ActiveCell range instead... So change ActiveCell in your script for a reference to the Row variable (with its new name...): 您的脚本正在与ActiveCell范围进行交互...因此,请在脚本中更改ActiveCell以引用Row变量(使用其新名称...):

If Not IsEmpty(Row.Value) Then

And see what happens! 看看会发生什么!

Furthermore I am wondering if Range("A9:A250").Rows actually contains anything as you dont explicitly refer to the Excel worksheet object. 此外,我想知道Range("A9:A250").Rows实际包含任何内容,因为您没有显式引用Excel工作表对象。 You better run this in debug mode to see if your local variables and objects actually refer to what you expect... 您最好在调试模式下运行此命令,以查看您的局部变量和对象是否实际引用了您所期望的...

I don't get what your code is meant to do, but I think that there are few problems in your code: 我不了解您的代码的用途,但我认为您的代码中很少有问题:

1) Avoid using variable name identical to the vba objects names, like "row", "column", "cell". 1)避免使用与vba对象名称相同的变量名称,例如“行”,“列”,“单元格”。 It may cause bugs, so better use same names like "myrow", "row1", "rw" etc. 它可能会导致错误,因此最好使用相同的名称,例如“ myrow”,“ row1”,“ rw”等。

2) If you want to make a loop on one of the "ITAG Open Interactions.xlsx" sheets, you must refer to it's name and specify the sheet, like "xlWrkBk.Worksheets(1).Range("A9:A250").Rows" 2)如果要在其中一个“ ITAG Open Interactions.xlsx”工作表上循环,则必须参考其名称并指定工作表,例如“ xlWrkBk.Worksheets(1).Range(“ A9:A250”) .Rows”

3) Before ActiveCell will refer to the iterated cell, you must activate it, like (row1.Activate). 3)在ActiveCell引用迭代单元之前,必须先将其激活,例如(row1.Activate)。 However, I prefer to use select and selection. 但是,我更喜欢使用select和selection。

4) When you open other excel application and create objects, at the end of the code you should close or release them, like "set xlWrkbk = nothing" or "xl.Application.Quit". 4)当打开其他excel应用程序并创建对象时,在代码末尾应关闭或释放它们,例如“ set xlWrkbk = none”或“ xl.Application.Quit”。

5) When using loop "For Each" you can just check if currently iterated range fulfil your coditions and then do specified actions. 5)使用循环“ For Each”时,您只需检查当前迭代的范围是否满足您的条件,然后执行指定的操作即可。 You don't have to return to the right column, so you can skip the outer if statement. 您不必返回到右列,因此可以跳过外部的if语句。

I don't exacly know what you want to do with the strIMresult, however whole code should look like that: 我不完全知道您要如何使用strIMresult,但是整个代码应如下所示:

Sub AdjacentRow()

Dim xlWrkBk As Excel.Workbook
Dim xl As Excel.Application

Set xl = CreateObject("Excel.Application")
Set xlWrkBk = GetObject("D:\Excel\a.xlsx")

Dim i, j As Integer
Dim strIMresult As String
Dim row1 As Excel.Range

xlWrkBk.Worksheets(1).Activate
For Each row1 In xlWrkBk.Worksheets(1).Range("A9:A250").Rows
    row1.Select
    If Not IsEmpty(Selection) Then
        'move to adjacent cell
        Selection.Offset(0, 1).Select
        strIMresult = Selection
        'I dont understand what the code should do with the value from b column,
        'so you should add here some code.
        'For now I just added code that print string value in the message box
        MsgBox (strIMresult)
    End If
Next

Set xlWrkBk = Nothing
xl.Application.Quit

End sub 结束子

This is what worked: 这是有效的:

Sub AdjacentRow()

    Dim xlWrkBk As Excel.Workbook

    Dim xlsht As Excel.Worksheet
    Dim xl As Excel.Application

    Set xl = CreateObject("Excel.Application")

    Set xlWrkBk = GetObject("C:\Users\My_Account\Desktop\tst.xlsx")
    Set xlsht = xlWrkBk.Worksheets(1)

    Dim i, j, FirstCell, LastCell As Integer
    Dim strIMresult As String


    Dim Cell, Row, Column As Excel.Range

    For Each Row In xlsht.Range("A9:A250").Rows
        For Each Cell In Row.Cells

            If Len(Cell.Value) > 0 Then
                'move to adjacent cell
                ActiveCell.Offset(0, 1).Select

                If Len(ActiveCell.Value) > 0 Then
                    'copy the value
                    strIMresult = ActiveCell.Value

                    Debug.Print strIMresult
                Else
                    ActiveCell.Offset(0, -1).Select
                End If
            End If
        Next Cell
    Next Row
End Sub

Ultimately the fix was in the following 最终,解决方法如下

For Each Row In Range("A9:A250").Rows

changing to 更改为

For Each Row In xlsht.Range("A9:A250").Rows

to specify the work sheet that had to be looped through. 指定必须遍历的工作表。 Then adding, 然后添加

For Each Cell In Row.Cells

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我对这个 Excel vba 做错了什么 - What am I doing wrong with this Excel vba Excel VBA:在for循环中跳转:“ Next for For” –我在做什么错? - Excel VBA: Jump inside a for loop: “Next without For” – What am I doing wrong? 我究竟做错了什么? 使用Excel VBA删除重复项 - What am I doing wrong? Removing duplicates using Excel VBA 我在excel行循环的拆分中做错了什么? - What am I doing wrong in this split for excel rows loop? 尝试将(仅)唯一值从列传递到 VBA 中的字典。 验证未发生。 我错过了什么? - Trying to pass (only) unique values from column to dictionary in VBA. Validation not ocurring. What am I missing? 我正在尝试确定 excel 中的形状是否从 VBA 中连接了一个连接器。 可以做到吗? - I am trying to identify whether a shape in excel has a connector attached to it from within VBA. Can it be done? 在Excel VBA宏中创建一个新行(我做错了什么?) - Creating a new row in Excel VBA macro (what am I doing wrong?) Excel VBA Find函数未返回整数值,看不到我在做什么 - Excel VBA Find function not returning an integer value, can't see what I am doing wrong VBA创建数据透视表,类型不匹配? 我究竟做错了什么? - VBA to Create PivotTable, Type Mismatch? What Am I Doing Wrong? VBA将多列转换为两列-我在做什么错? - VBA Transform Many Columns to Two - What am I doing wrong?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM