【问题标题】:Problems getting "with selection" to work使“选择”起作用的问题
【发布时间】:2019-09-19 09:01:57
【问题描述】:

我正在编写一个 excel vba 代码来导入和操作 CSV 文件中的一些数据。突然间,我的一部分代码不再工作了,尽管它以前可以正常工作。

关于 range.select 和之后的 selection.Interior.Pattern = xlSolid

我曾尝试将相同的一小部分代码复制到不同的工作簿,在这里它工作得非常完美。

Dim iPhase As Integer
iPhase = Application.WorksheetFunction.CountIf(Range("A:A"), "Phase")
Dim h As Integer
h = 1

Range("A6").Select

Do Until h > iPhase
    Cells.Find(What:="Phase", after:=ActiveCell, LookIn:=xlFormulas, LookAt _
    :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False).Activate
    ActiveSheet.Range(ActiveCell, ActiveCell.Offset(0, 16)).Select
    With selection.Interior
        .Pattern = xlSolid
        .Interior.PatternColorIndex = xlAutomatic
        .Interior.ThemeColor = xlThemeColorAccent6
        .Interior.TintAndShade = 0
        .Interior.PatternTintAndShade = 0
    End With
    With selection.Font
        .Bold = True
    End With
    h = h + 1
Loop

我得到一个编译错误:预期的函数或变量@"selection.interior"

【问题讨论】:

  • 不要使用.Select.SelectionHow to avoid using Select in Excel VBA
  • 还有两件事 [1.] 你假设Cells.Find 将返回一个结果。检查它是否发现了什么。您可能希望看到THIS 了解如何做到这一点[2.] I get a compile error: Expected function or variable @"selection.interior" 如果您复制代码并按原样粘贴,那么您的selection 有一个小的s。这意味着您已经声明了一个具有相同名称的变量/模块/类等。你也需要避免这种情况......

标签: excel vba


【解决方案1】:

cmets 已经确定了您的代码存在的问题;但这里是使用FilterSpecialCells 来选择可见数据的替代方法。注释包含在代码中。

Sub FliterWithConditionalFormatting()
Dim rng As Range

'properly defing and reference your workbook and worksheet, change as requiried
Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1").CurrentRegion

'The WITH..END WITH statement allows you to shorten your code and avoid using SELECT and ACTIVATE
With rng
     .AutoFilter Field:=1, Criteria1:="Phase", Operator:=xlAnd 'filter the rng

    'set the range, to conditionally format only the visible data, skipping the header row
    With .Range(Cells(2, 1), Cells(rng.Rows.Count, 17)).SpecialCells(xlCellTypeVisible)

        With .Interior
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
            .Color = xlThemeColorAccent6
            .TintAndShade = 0
            .PatternTintAndShade = 0
        End With

        With .Font
            .Bold = True
        End With
    End With

    .AutoFilter 'Remove the filter
End With
End Sub

【讨论】:

    猜你喜欢
    • 2011-12-04
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2020-05-01
    相关资源
    最近更新 更多