Range().Cells().Row

Range().Cells().Row

我被下面的代码困扰

Dim xTRrow as Integer
Dim xTitle as String
Dim xSht as Worksheet
xTRrow = xSht.Range(xTitle).Cells(1).Row

我想知道最后一行是做什么的。特别是 .Row。在这种情况下,我如何才能逐行 运行 VBA 代码来找出特定代码行的作用?我猜代码有问题。我试图显示 xTRrow 应该是一个整数。但是屏幕上没有任何内容。我想知道最后一个选项 .Row 的作用。

除了使用 F8 单步执行代码外,您还可以使用 debug.print 显示给定行前后相关变量的值。也就是说,当您使用 VBA 时,您将能够识别什么是对象和方法。假设代码工作正常并且所有变量和对象都变暗并正确设置:

xSht.Range(xTitle).Cells(1).Row

细分如下:

xSht :包含 sheet 的变量(sheet 我们不知道,因为您的问题中缺少那部分代码)

xTitle:可能是 named range 的名称(我们不知道哪个范围,因为您的问题中缺少您的那部分代码)

Cells(1):小区号; 1 上述命名范围

Row:相关单元格的行

所以 xTRrow 应该是相关单元格的行号。 (顺便说一句,它真的应该 Dimmed as Long 因为 Excel 可以有比 Integer 允许的行更多的行

行麻烦

描述

变量'xTRrow'等于'1的'row' ]'st 'cell' 工作表中的 'range 'xTitle' 'xSht'。您可以通过定义缺失数据使其工作。

代码

Option Explicit

Sub RowTrouble()

  Dim xSht As Worksheet  ' A Worksheet
  Dim xTitle As String   ' A Range Address (or a Named Range)
  Dim xTRrow As Long     ' A Row - rows are best declared as Long.

'  ' Your code (not yet working)
'  xTRrow = xSht.Range(xTitle).Cells(1).Row

  ' Define the range
  xTitle = "A1:D1"

  ' Create a reference to the worksheet with the name "Sheet1"
  Set xSht = ThisWorkbook.Worksheets("Sheet1")

  ' Your code working
  xTRrow = xSht.Range(xTitle).Cells(1).Row

  ' To display the result in the immediate window
  Debug.Print "The first row in my workbook's range (" & xTitle _
      & ") is equal to " & xTRrow & "."

  ' To display the result in a message box:
  MsgBox "The first row in my workbook's range (" & xTitle _
      & ") is equal to " & xTRrow & "."

  ' To display the result in the sheet:
  xSht.Range("A1") = "The first row in my workbook's range (" & xTitle _
      & ") is equal to " & xTRrow & "."

End Sub

如何

打开一个新的工作表。转到 Visual Basic 编辑器并将新模块插入到工作表中。 Copy/paste把例子放进去。打开immediatewindow就可以看到结果了。 运行代码。

逐行

Too 在 Debug select Step Into 下逐行循环代码,或者只使用 'F8':