excel - 使用 HSL 功能时如何修复 "Sub or Function not defined"

标签 excel vba colors rgb hsl

我正在尝试使用 HSL 而不是 RGB 设置某些单元格的内部颜色。

从微软的这份文档来看,它非常简单:
https://docs.microsoft.com/en-us/office/client-developer/visio/hsl-function

语法很简单 HSL(** 色调 **, ** 饱和度 **, ** 亮度 ** )

那么,为什么我的 VBA 会告诉我 sub 或 function 没有定义?

这两行代码都会出现相同的错误:

Range("A1").Interior.Color = HSL(160, 240, 120)

Range("A1").Interior.ColorIndex = HSL(160, 240, 120)

最佳答案

这是使用 Windows API 在 VBA 中的 RGB → HSL 之间转换的另一种方法。由于它是“经典 Windows”功能,因此它有几个特点。
RGB 到 HSL 与 ColorRGBToHLS

ColorRGBToHLS is an Windows API function which therefore uses an outdated color range that's been carried forward since the 1980's (originally used in a long-defunct program called MS Chart). You may be familiar with converting R/G/B values between percentages and values out of 255.

  • However in this case the conversion must be to/from values out of 240, not 255.
  • Just to further confuse us here in the future, they used notation of HLS instead of more-common HSL (and hex color strings are 0xBBGGRR instead of #RRGGBB).

tl;博士
Option Explicit

Public Declare PtrSafe Sub ColorRGBToHLS Lib "shlwapi.dll" (ByVal clrRGB As Long, _
    wHue As Integer, wLuminance As Integer, wSaturation As Integer)

Function rgb_to_hsl(r As Integer, g As Integer, b As Integer)
  Dim h As Integer, s As Integer, l As Integer
  ColorRGBToHLS RGB(r, g, b), h, l, s
  h = 360 * (h / 239)
  s = 100 * (s / 240)
  l = 100 * (l / 240)
  rgb_to_hsl = "hsl(" & h & "," & s & "%," & l & "%)"
End Function
...和一个 demo :
Sub test()
  Debug.Print rgb_to_hsl(255, 180, 63)  'returns "hsl(36,100%,62%)"
End Sub
顺便说一句,API 也有一个 ColorHLSToRGB 功能。
80 年代对于计算机 Nerd 来说是一个疯狂(经常令人困惑)的时代。有趣的事实:比尔盖茨嫁给了他雇用的第一位女程序员。

关于excel - 使用 HSL 功能时如何修复 "Sub or Function not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58432921/

相关文章:

Excel VBA - 如何添加动态数组公式

excel - 使用 ADO 和 Delphi 从 XLS 文件导入数据

vba - Microsoft Excel – 如何将每 n 行的单元格复制到不同的工作表

database - 避免两个字段具有相同的值

Java 重新着色 JProgressBar 一根像素线

javascript - 根据另一个元素的颜色更改 SVG 的颜色?

excel - 使用 VBA 将 Excel (2016) 文件中的图片导出为 gif 最终出现黑屏

vba - 我在重置单元格值 excel 时做错了什么

java - 访问 XSSFWorkbook 中的调色板

python - 新手 - 将 49 张 Excel 工作表读入数据框