0

我需要找到某些数字(由用户给出)之间的行以在屏幕上显示它们以便可以打印。

例如:用户输入 104822000011 和 104822000020 作为fromto值。然后我需要在另一个工作表中搜索这些之间的任何数字。工作表中的数据来自数据库。我需要返回给定数字之间的行中的所有数据。

我对VBA知之甚少,所以如果这可以用工作表函数来完成,那将是可取的。我用谷歌搜索并尝试了一些东西,但它们似乎都不容易做到或不起作用。有人可以在这里帮我一点吗?

4

2 回答 2

2

Let's assume you have your data on the worksheet dataWS, with row numbers in column A and data in column B

On another worksheet, you input your values from in A1 and to in B1

Then in A2 =IF($A1<$B$1,$A1+1,""), which will display the row number you want to display on this row.

Next, in B2 retrieve the data with =IF($A2="","",VLOOKUP($A2,dataWS!A:B,2,FALSE)). Copy the formulas in A2:B2 to the rows below, and you should be set.

Should you want to do it with VBA, you could use the following bit of code (that assumes the Ids in your data are ordered properly). Be also aware that it does not empty the target area before writing the new data.

Public Sub getData()

Dim currentId As Long
Dim toId As Long

Dim wsTarget As Worksheet
Dim targetIdCol As Integer
Dim targetDataCol As Integer

Dim wsSource As Worksheet
Dim sourceIdCol As Integer
Dim sourceDataCol As Integer

Dim readRow As Long
Dim writeRow As Long


Set wsTarget = ThisWorkbook.Worksheets("Sheet2") ' name of the target worksheet
targetIdCol = 1    'number of the column where the ids are to be written (a=1)
targetDataCol = 2   'number of the column where the data is to be written

Set wsSource = ThisWorkbook.Worksheets("Sheet1") ' name of the source data worksheet
sourceIdCol = 1    'number of the column where the ids are to be read(a=1)
sourceDataCol = 2   'number of the column where the data is to be read


currentId = wsTarget.Range("A1").Value  'cell in which the from is specified (here "A1" of target worksheet)
toId = wsTarget.Range("B1").Value 'cell in which the to is specified (here "B1" of target worksheet)


readRow = 1   'row at which the data should start to be read
writeRow = 2   'row at which the data should start to be written


While (wsSource.Cells(readRow, sourceIdCol) <> "") And (currentId <= toId)

    If currentId = wsSource.Cells(readRow, sourceIdCol).Value Then
        wsTarget.Cells(readRow, targetIdCol) = wsSource.Cells(readRow, sourceIdCol).Value
        wsTarget.Cells(readRow, targetDataCol) = wsSource.Cells(readRow, sourceDataCol).Value
        readRow = readRow + 1
    Else

        If currentId > wsSource.Cells(readRow, sourceIdCol).Value Then
             readRow = readRow + 1
      Else
          currentId = currentId + 1
      End If
    End If

Wend



End Sub
于 2012-12-05T14:02:41.693 回答
1

是的,您可以通过复制行(您不想要的)或 VBA 来做到这一点。而且我相信 VBA 是一个不错的选择。

但是如果记录号是严格的数字并且没有太多数据要显示,我有一个使用数据透视表的愚蠢方法。

您可以添加一个引用数据表的数据透视表。然后将所有字段拖到行标签上。然后对于每个字段设置,在布局中选择“以表格形式显示项目标签”并删除所有小计。它现在应该看起来与原始数据相似。

然后您可以选择记录编号上的任何位置,然后在行标签上选择“标签过滤器 ==> 之间”。然后输入你的 from 和 to 值。

于 2012-12-10T05:28:13.203 回答