Excel的VBAinput框 – select范围(types8),但不是一个固定的范围,即A1不是$ A $ 1

我目前有一个Inputbox VBA代码中的以下行:

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)

但是,当我select单元格时,它会自动input例如$A$1 。 这可以改变,而不需要用户手动删除$,这样Inputbox会自动获取A1的单元格引用吗?

这是一个自动VLookupmacros的一部分,除了整个列中的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会从例如单元格A2开始,但是因为我们正在使用dynamic列表,当公式被复制到列表中时,我需要将查找值更改为A3,A4,A5等。 通过使用$ A $ 2的input框,查找公式仅查看该单元格引用。

正如Tim所说,你的问题不在InputBox中。 相反,当您一次为整个范围设置公式时,它会为每个单元格的公式使用FirstRow 。 理想情况下,您可以使用.FormulaR1C1来设置公式。 这将允许您在一个通过相关的公式。

下面的解决scheme只是修改您的代码,在第一个单元格中放置一个非相对地址,然后在其余单元格中设置公式与第一个单元格中的公式相同。 当你指定这样的公式时,它会使它们相对:

 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 

您的问题不是与InputBox,而是Address()方法的行为。

默认情况下,不带参数的Address()返回绝对地址。

 Cells(FirstRow, myValues.Column).Address(False,False) 

将返回“非固定”范围地址。