在VBA中,如何读取图像中每个像素的颜色值?
我在VB 6.0中找到this solution,但它不直接应用于VBA。
答案 0 :(得分:9)
尝试在此网站上发布的解决方案: http://sim0n.wordpress.com/2009/03/27/vba-q-how-to-get-pixel-colour/
我不得不将ByRef更改为ByVal,但除此之外它运作良好。使用Insert>插入图片图片并为点击事件指定一个宏。我刚刚将单元格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
要使用它,请在工作表中放置图片,右键单击图像并将此宏指定给它。