Excel vba从单元格内容中选择

时间:2016-09-02 18:31:54

标签: excel excel-vba formatting vba

对于这里的向导来说,这可能是一个非常基本的问题。

我试图通过根据输入的信息计算工作表中的特定单元格,并且我对该部分的代码工作正常。通过输入名称,我会在另一个单元格中获得一个单元格引用,例如Y5。我试图选择该值(单元格地址)作为定义的变量celref。然后在我想要更新的工作表上,我希望celref的单元格接收指定的格式。我使用的代码是:

Sub confirm()
Dim NAM As String
Dim celref As String
Worksheets("Morning").Select
NAM = Range("C3").Value
celref = Range("D3").Value
answer = MsgBox("Confirm sign in for " + NAM, vbYesNo + vbQuestion, "Confirm  Sign In")
If answer = vbNo Then GoTo Bye

    Worksheets("details").Select
Range(celref).Select      '<========= This is where I get the error!
With Selection.Font
    .ThemeColor = xlThemeColorDark1
    .TintAndShade = 0
End With
With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .ThemeColor = xlThemeColorLight1
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
Selection.Font.Bold = True

之后会有更多代码,但它似乎是导致问题的范围选择。我正在制作哪个新手错误?

1 个答案:

答案 0 :(得分:0)

如果您希望以更好的形式实现这一目标,请尝试以下方式:

Sub confirm()
    Dim morningWS, detailsWS As Worksheet
    Dim NAM, celref As String

    Set morningWS = ThisWorkbook.Sheets("Morning")
    Set detailsWS = ThisWorkbook.Sheets("details")
    celref = morningWS.Range("D3").Value
    NAM = morningWS.Range("C3").Value

    answer = MsgBox("Confirm sign in for " + NAM, vbYesNo + vbQuestion, "Confirm  Sign In")
    If answer = vbNo Then GoTo Bye

    With detailsWS.Range(celref)
        With .Font
            .ThemeColor = xlThemeColorDark1
            .TintAndShade = 0
            .Bold = True
        End With
        With .Interior
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
            .ThemeColor = xlThemeColorLight1
            .TintAndShade = 0
            .PatternTintAndShade = 0
        End With
    End With

这样可以清楚显示您引用的单元格,并且可以让您更轻松地编辑内容而不会出错。

另一种方法可以实现这一目标:

Sub confirm()
    Dim morningWS, detailsWS As Worksheet
    Dim NAM As String
    Dim celref as Range

    Set morningWS = ThisWorkbook.Sheets("Morning")
    Set detailsWS = ThisWorkbook.Sheets("details")
    Set celref = detailsWS.Range(morningWS.Range("D3").Value) 'making celref a range object
    NAM = morningWS.Range("C3").Value

    answer = MsgBox("Confirm sign in for " + NAM, vbYesNo + vbQuestion, "Confirm  Sign In")
    If answer = vbNo Then GoTo Bye

    With celref 'celref is the object and doesnt need to be otherwise addressed
        'rest of the code