【问题标题】:Range().Cells().RowRange().Cells().Row
【发布时间】:2018-11-23 15:37:29
【问题描述】:
被下面的代码困扰
Dim xTRrow as Integer
Dim xTitle as String
Dim xSht as Worksheet
xTRrow = xSht.Range(xTitle).Cells(1).Row
我想知道最后一行是做什么的。特别是.Row。在这种情况下,如何逐行运行 VBA 代码以找出特定代码行的作用?我想代码有问题。我试图显示xTRrow,它应该是一个整数。但是屏幕上什么也没有。我想知道最后一个选项 .Row 是做什么的。
【问题讨论】:
标签:
excel
vba
worksheet-function
【解决方案1】:
除了使用F8 单步执行代码之外,您还可以使用debug.print 在给定行之前和之后显示相关变量的值。也就是说,当您使用 VBA 时,您将能够识别什么是对象和方法。假设代码工作正常并且所有变量和对象都变暗并正确设置:
xSht.Range(xTitle).Cells(1).Row
分解如下:
xSht :包含工作表的变量(我们不知道哪个工作表,因为您的问题中缺少您的代码部分)
xTitle:可能是named range 的名称(我们不知道哪个范围,因为您的问题中缺少您的代码部分)
Cells(1):手机号;上述命名范围的1
Row: 有问题的单元格所在的行
所以xTRrow 应该是相关单元格的行号。 (顺便说一句,它真的应该是 Dimmed 和 Long,因为 Excel 可以有比 Integer 允许的更多行
【解决方案2】:
行问题
说明
变量'xTRrow'等于'1'st'单元格的'row' >' 的 '范围 '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 编辑器并将一个新模块插入到工作表中。将示例复制/粘贴到其中。打开立即窗口可以看到结果。运行代码。
一行一行
在Debug下逐行循环代码选择Step Into或只使用'F8':