在 VBA 中,如何读取图像中每个像素的颜色值?
我在 VB 6.0 中找到了这个解决方案,但它并不直接应用于 VBA。
尝试在此站点上发布的解决方案:http: //sim0n.wordpress.com/2009/03/27/vba-q-how-to-get-pixel-colour/
我不得不将 ByRef 更改为 ByVal,但除此之外它运行良好。使用“插入”>“图片”插入图片并将宏分配给单击事件。我刚刚将单元格 A1 的颜色设置为您单击的颜色,但我相信您明白了。
#If VBA7 Then
Private Declare PtrSafe Function GetPixel Lib "gdi32" (ByVal hdc As LongPtr, ByVal x As Long, ByVal y As Long) As Long
Private Declare PtrSafe Function GetCursorPos Lib "user32" (ByRef lpPoint As POINT) As LongPtr
Private Declare PtrSafe Function GetWindowDC Lib "user32" (ByVal hwnd As LongPtr) As LongPtr
#Else
Private Declare Function GetPixel Lib "gdi32" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long) As Long
Private Declare Function GetCursorPos Lib "user32" (ByRef lpPoint As POINT) As Long
Private Declare Function GetWindowDC Lib "user32" (ByVal hwnd As Long) As Long
#End If
Private Type POINT
x As Long
y As Long
End Type
Sub Picture1_Click()
Dim pLocation As POINT
Dim lColour As Long
Dim lDC As Variant
lDC = GetWindowDC(0)
Call GetCursorPos(pLocation)
lColour = GetPixel(lDC, pLocation.x, pLocation.y)
Range("a1").Interior.Color = lColour
End Sub
要使用它,请将图片放在工作表中,右键单击图像并将此宏分配给它。