简体   繁体   中英

Incorporate String into a Range (Excel VBA)

I am working with a code to have a user enter in a year, to which excel would then find in a row, and then autofill the formula in that column. I have managed to be able to get the input and column aspect down, but am struggling with how to incorporate my sting into a range. Please help!

Code below.

Sub Copy_formula()
    NewPageName = InputBox("Enter in Year")

    Dim rFind As Range

    Sheets("data_calc").Select

    With Range("A2:AH2")
        Set rFind = .Find(What:=NewPageName, LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
        If Not rFind Is Nothing Then
            MsgBox rFind.Column
        End If

    End With

    Selection.AutoFill Destination:=Range(Cells(3, "rFind"), Cells(2393, "rFind"))
    Range(Cells(3, "rFind"), Cells(2393, "rFind")).Select
End Sub

"rFind" within double quotes is a String which VBA will try to convert to a column number within a Cells() statement. As columns run from "A" to "XFD", anything beyond that should cause an error. So loose the double quotes.

However, that won't entirely solve your problem. The default return for a Range object is its .Value property.

What you want is the Range.Column property.

So change your Range(Cells(3, "rFind"), Cells(2393, "rFind")) to:

Range(Cells(3, rFind.Column), Cells(2393, rFind.Column))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM