Excel VBA查找地址并分配给变量然后重用值

时间:2017-01-08 07:37:01

标签: excel vba excel-vba

我试图查找单元格上是否有给定标题,将该单元格的地址传递给变量并使用此位置调整列的大小。我之所以这样做,是因为我正在编写几个可以改变列位置的函数。如果有人能看一看并告诉我自己做错了什么,我会很感激。

Option Explicit

Sub adjustColumns()

Dim PONumberCell As String
Dim PONumberAddress As Range
Dim TopLabelinColumn As Range

For Each TopLabelinColumn In Range("A1:Z1").Cells
    If TopLabelinColumn Like "PO_NUMBER" Then TopLabelinColumn.Value = "PO"
    PONumberCell = TopLabelinColumn.Address

    Set PONumberAddress = PONumberCell
    PONumberAddress.ColumnWidth = 70

Next TopLabelinColumn

End Sub

2 个答案:

答案 0 :(得分:3)

在OP的进一步请求后编辑

您将一个Range对象(例如PONumberCell)与String变量(如PONumberAddress)混淆,所以

Set PONumberAddress = PONumberCell

无效,因为您尝试将object变量分配给String

但是你可以更有效地避免循环并使用Find()方法

Option Explicit

Sub adjustColumns()
    Dim PONumberAddress As String
    Dim PONumberCell As Range

    Set PONumberCell = Range("A1:Z1").Find(what:="PO_NUMBER", LookIn:=xlValues, lookat:=xlPart, MatchCase:=False)
    If Not PONumberCell Is Nothing Then
        With PONumberCell
            .value = "PO"
            PONumberAddress = .Address
            .EntireColumn.ColumnWidth = 70
        End With
    Else
        Set PONumberCell = Range("A1:Z1").Find(what:="PO", LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False) '<--| if it didn't find "PO_NUMBER" then it seaches for a complete match of "PO"
        If Not PONumberCell Is Nothing Then PONumberCell.EntireColumn.ColumnWidth = 70
    End If
End Sub

答案 1 :(得分:1)

根据上述评论,您的代码中会出现一些错误:

  1. 设置 PONumberAddress 范围,您需要使用括号中的地址字符串语法PERLBREW_CONFIGURE_FLAGS="-de -f /home/USERNAME/config_dont_use_nlink.sh" perlbrew install perl-5.24.0

  2. 要设置列宽,请使用:Set PONumberAddress = Range(PONumberCell)

  3. 根据您的帖子,我认为您只想对标题文字为&#34; PO_NUMBER&#34;的列进行此操作,因此您需要下面的所有代码PONumberAddress.Columns.ColumnWidth = 70If

  4. <强>代码

    If TopLabelinColumn.Value Like "PO_NUMBER" Then