我有一個作業簿 UserFileBook,其中包含名稱“版本”,它只是指一個數字(它不指任何范圍,在名稱管理器中它只是“指 = 5”)。我正在嘗試將此數字與不同作業簿的版本號進行比較。當我將 UserFileBook 的“版本”作為實際命名范圍時(它參考單元格 C1,其中的值為 5),一切正常。但是 IdiotUser 可以編輯該值或直接在作業表上將其洗掉,因此我將其設定為僅參考一個數字,因此只能通過管理器進行編輯。我現在有沒有辦法獲得該名稱的值并從另一個 WB 中更改它?目前我正在嘗試這個:
Sub CheckVersionNumber(Vers As Long)
'Checks to see if this version is compatible with the UW version
Dim wb As Workbook
Set wb = UserFileBook
Dim UWVers As Long
UWVers = wb.Names("Version").Value 'Breaks here
'Version information is in the range "Version" on UW
If UWVers < Vers Then
GoTo LowerVersion
Else
If wb.Names("Version") > Vers Then 'tried this originally and also breaks, also if .Value is added
GoTo UpperVersion
End If
End If
Exit Sub
我還嘗試與 wb.Range("Version") 甚至 wb.Worksheets("Sheet 1").Range("Version) 進行比較,但這些也不起作用。我如何參考(和更改)“Version”的值" 如果 USerFileBook 不參考范圍?
uj5u.com熱心網友回復:
您不能使用.Range,因為Version它不是一個范圍。這是一個命名公式。
但你可以評估它:
UWVers = wb.Worksheets(1).Evaluate("Version")
要使用不同的值更新命名公式,請說999:
wb.Names.Add "Version", 999
順便說一句...由于您在用戶更改解決方案設定時遇到困難,您可能希望探索使用CustomXMLParts.Add來存盤您的Version. CustomXMLParts 沒有用戶界面,但它們存盤在作業簿中。訪問它們的唯一方法是通過代碼。普通用戶永遠不會看到您以這種方式存盤的版本號。事實上,大多數高級開發人員也永遠不會找到它。
uj5u.com熱心網友回復:
您可以使用wb.Names("Version").Value,但它回傳一個字串 >> =999。因此,您必須在分配給 long 值之前省略等號。
如果要對普通用戶隱藏名稱,可以將名稱的可見性(第一次添加時)設定為 false。然后名稱不會顯示在名稱管理器中。
我會創建一個函式和一個子。
'---> get current version
Public Function getVersion(wb As Workbook, Optional throwError As Boolean = False) As Long
On Error Resume Next 'in case version does not exist function will return 0
'remove =-sign as from returned value to return a long value
getVersion = Replace(wb.Names("Version").Value, "=", vbNullString)
'if useful you could throw an error here
If Err <> 0 And throwError = True Then
Err.Clear: On Error GoTo 0
Err.Raise vbObjectError, , "Version hasn't been set for this workbook"
End If
On Error GoTo 0
End Function
'--->> set version
Public Sub setVersion(wb As Workbook, newVersion As Long)
On Error Resume Next 'in case version doesn't yet exists
wb.Names("Version").Value = newVersion
If Error > 0 Then
Err.Clear: On Error GoTo 0
'Version name does not yet exist --> add as invisible name
wb.Names.Add "Version", "=" & newVersion, Visible:=False
Else
On Error GoTo 0
End If
End Sub
這是您使用它們的方式:
Sub testVersionAsNameConstant()
Debug.Print getVersion(ThisWorkbook, False)
'comment this out if you don't want to see the error
Debug.Print getVersion(ThisWorkbook, True)
setVersion ThisWorkbook, 1
Debug.Print getVersion(ThisWorkbook), "should be 1"
setVersion ThisWorkbook, 2
Dim checkValue As Long
checkValue = 1
Debug.Print getVersion(ThisWorkbook) > checkValue, "should be true"
Debug.Print getVersion(ThisWorkbook) = checkValue, "should be false"
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/472662.html
