根据另一列中的值在一列中选择一组单元格

时间:2009-01-14 14:17:06

标签: excel vba excel-vba

我有以下表格中的大量数据


A   B
1   stuff1
6   stuff2
3   stuff3
1   stuff4
1   stuff5
7   stuff6
3   stuff7
2   stuff8
.   .
.   .
.   .
5   stuffn

我想要的是一些vba代码,它将选择B中A列中具有“1”的所有单元格 - 我将使用此集合在我的代码的另一部分中执行某些任务

任何想法?

谢谢

3 个答案:

答案 0 :(得分:0)

我不确切地知道你在longrun中想要做什么,但是对于这一步,你可以在C列=if(a1=1,b1,"")中执行此操作,然后在列c上应用过滤器并选择选项非空白
然后你可以选择整个列c

答案 1 :(得分:0)

这应该有效:

Sub SelectCellsInColBBasedOnColA()
    Dim TheSheet As Worksheet
    If TypeOf ActiveSheet Is Worksheet Then
        Set TheSheet = ActiveSheet
    Else
        Exit Sub
    End If

    Dim Row As Integer
    Dim CellsToSelect As String
    For Row = 1 To TheSheet.Range("A" & CStr(TheSheet.Rows.Count)).End(xlUp).Row
        If TheSheet.Range("A" & CStr(Row)).Value = 1 Then
            If CellsToSelect <> "" Then CellsToSelect = CellsToSelect & ","
            CellsToSelect = CellsToSelect & "B" & CStr(Row)
        End If
    Next Row
    TheSheet.Range(CellsToSelect).Select
End Sub

答案 2 :(得分:0)

总有ADO。

'Reference: Microsost ActiveX n.n Object Library '
'but it is not necessary, Dim rs and cn as object '
'if you do not wish to use a reference '

Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection

'From: http://support.microsoft.com/kb/246335 '

strFile = Workbooks(1).FullName
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
    & ";Extended Properties=""Excel 8.0;HDR=No;IMEX=1"";"

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

cn.Open strCon

'Substitute a name range for [Sheet1$] '
'or include a range of cells : [Sheet1&A1:C7] '
'F1 is field 1, because we have no header (HDR: No) '
strSQL = "SELECT * FROM [Sheet3$] " _
       & "WHERE F1=1"

rs.Open strSQL, cn

'Write out to another sheet '
Worksheets(2).Cells(2, 1).CopyFromRecordset rs