Excel VBA使用户select范围variables永久

我有一个脚本,将朱利安date转换为公历date。 我应该能够点击包含我的朱利安date的范围,然后select我想插入我的公历date的范围。 唯一的问题是,一旦我把第一个选定的范围设置为JD(朱利安date),我似乎无法分配一个新的选定范围。

例如,如果我selectB:B作为我的JD范围,那么JD = 2。

那么如果我selectD:D作为GD(公历date)的范围,那么GD应该= 4,但它仍然等于2.我不确定在完成这部分之后还有什么会出错。我现在卡在这里了。 谁能提供任何见解? 任何帮助表示赞赏!

Sub Julian_to_Gregorian() Dim rng As Range, col As Range, cols As Range, arr Dim sht As Worksheet, shet As Worksheet, hdr As Long, yn As Long, LastRow As Long Dim dest As Range On Error Resume Next Set rng = Application.InputBox( _ Prompt:="Please select the column that contains the Julian Date. " & vbNewLine & _ " (eg Column A or Column B)", _ Title:="Select Julian Date Range", Type:=8) On Error GoTo 0 jd = Selection.Column 'pjd = jd.Column hdr = MsgBox("Does your selection contain a header?", vbYesNo + vbQuestion, "Header Option") Set dest = Application.InputBox( _ Prompt:="Please select the column that the Gregorian Date will be placed in. " & vbNewLine & _ "(A new column will be inserted in this location, preserving the current data in this location.)", _ Title:="Select Destination Range", Type:=8) gd = Selection.Column If dest Is Nothing Then Exit Sub 'gd = Selection.Column Set sht = dest.Parent Set shet = rng.Parent On Error GoTo 0 'yn = MsgBox("Do you want to insert a new column here?" & vbNewLine & _ ' "(Choosing 'No' will replace the current cells in your selected range." & vbNewLine & _ ' "All data in this range will be permanently deleted.)", vbYesNo + vbQuestion, "Destination Range Options") LastRow = shet.Cells(Rows.Count, jd).End(xlUp).Row Application.ScreenUpdating = False 'With Range(Cells(1, 3), Cells(1, 2 + Range("B1"))).EntireColumn With Cells(1, gd).EntireColumn .Insert Shift:=xlToRight End With 'gd.EntireColumn.Insert xlRight gd = gd - 1 For i = 2 To LastRow Cells(i, gd).Value = "=DATE(IF(0+(LEFT(" & Cells(i, jd) & ",2))<30,2000,1900)+LEFT(" & Cells(i, jd) & ",2),1,RIGHT(" & Cells(i, pjd) & ",3))" Next i End Sub 

我没有testing你的其他代码,但要得到正确的列:

  1. 更换

jd = Selection.Columnjd = rng.Column

  1. 更换

gd = Selection.Column with gd = dest.Column

代码不起作用的原因很简单:在提示期间激活的select在表单中不是“真实”的select,它们只对提示有效。 提示后,提示之前的select将再次激活,因此,jd和gd将始终等于执行macros之前所选单元格的列。