我的VBA
代码Inputbox
目前有以下一行:
Set myValues = Application.InputBox("Please select on the spreadsheet the first cell in the column with the values that you are looking for:", Type:=8)
然而,当我选择单元格时,它会自动输入例如$A$1
。如果用户不必手动删除$,是否可以更改此内容,以便Inputbox
会自动将单元格引用选为A1
?
它是自动VLookup
宏的一部分,除了在整列中修复的VLookup
值之外,它可以完美地工作。
提前致谢。
更新 - 以下是完整代码:
Dim FirstRow As Long
Dim FinalRow As Long
Dim myValues As Range
Dim myResults As Range
Dim myCount As Integer
Sub VlookupMacroNew()
Set myValues = Application.InputBox("Please select on the spreadsheet the first cell in the column with the values that you are looking for:", Default:=Range("A1").Address(0, 0), Type:=8)
Set myResults = Application.InputBox("Please select on the spreadsheet the first cell where you want your lookup results to start:", Type:=8)
myCount = Application.InputBox("Please enter the column number of the destination range:", Type:=1)
On Error Resume Next
myResults.EntireColumn.Insert Shift:=xlToRight
Set myResults = myResults.Offset(, -1)
FirstRow = myValues.Row
FinalRow = Cells(65536, myValues.Column).End(xlUp).Row
Range(myResults, myResults.Offset(FinalRow - FirstRow)).Formula = _
"=VLOOKUP(" & Cells(FirstRow, myValues.Column).Address & ", " & _
"'S:\Payroll\CONTROL SECTION\[Latest Data.xls]Sheet1'!$A$1:$B$100" & ", " & myCount & ", False)"
myValues将以例如但是,当我们使用动态列表时,我需要将查找值更改为A3,A4,A5等,因为公式将被复制到列表中。通过使用$ A $ 2的输入框,查找公式仅查看该单元格引用。
答案 0 :(得分:1)
您的问题不在于InputBox,而在于Address()
方法的行为。
默认情况下,没有参数的Address()
会返回绝对地址。
Cells(FirstRow, myValues.Column).Address(False,False)
将返回“非固定”范围地址。
答案 1 :(得分:1)
Tim说,你的问题不在于InputBox。相反,当您一次为整个范围设置公式时,它会为每个单元格的公式使用FirstRow
。理想情况下,您可以使用.FormulaR1C1
来设置公式。这将允许您在一次通过中使公式相对。
下面的解决方案只是修改您的代码,将非相对地址放在第一个单元格中,然后将剩余单元格中的公式设置为等于第一个单元格中的公式。当您指定类似的公式时,它会使它们成为相对的:
Sub VlookupMacroNew()
Set myValues = Application.InputBox("Please select on the spreadsheet the first cell in the column with the values that you are looking for:", Default:=Range("A1").Address(0, 0), Type:=8)
Set myResults = Application.InputBox("Please select on the spreadsheet the first cell where you want your lookup results to start:", Type:=8)
myCount = Application.InputBox("Please enter the column number of the destination range:", Type:=1)
On Error Resume Next
myResults.EntireColumn.Insert Shift:=xlToRight
Set myResults = myResults.Offset(, -1)
FirstRow = myValues.Row
FinalRow = Cells(65536, myValues.Column).End(xlUp).Row
Range(myResults, myResults.Offset(FinalRow - FirstRow)).Cells(1).Formula = _
"=VLOOKUP(" & Cells(FirstRow, myValues.Column).Address(False, False) & ", " & _
"'S:\Payroll\CONTROL SECTION\[Latest Data.xls]Sheet1'!$A$1:$B$100" & ", " & myCount & ", False)"
Range(myResults, myResults.Offset(FinalRow - FirstRow)).Formula = _
Range(myResults, myResults.Offset(FinalRow - FirstRow)).Cells(1).Formula
End Sub